问题:
I want to match a portion of a string using a regular expression and then access that parenthesized substring: 我想使用正则表达式匹配字符串的一部分,然后访问带括号的子字符串:
var myString = "something format_abc"; // I want "abc"
var arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);
console.log(arr); // Prints: [" format_abc", "abc"] .. so far so good.
console.log(arr[1]); // Prints: undefined (???)
console.log(arr[0]); // Prints: format_undefined (!!!)
What am I doing wrong? 我究竟做错了什么?
I've discovered that there was nothing wrong with the regular expression code above: the actual string which I was testing against was this: 我发现上面的正则表达式代码没有任何问题:我要针对的实际字符串是:
"date format_%A"
Reporting that "%A" is undefined seems a very strange behaviour, but it is not directly related to this question, so I've opened a new one, Why is a matched substring returning "undefined" in JavaScript? 报告“%A”未定义似乎是一种非常奇怪的行为,但它与该问题没有直接关系,因此我打开了一个新的代码, 为什么匹配的子字符串在JavaScript中返回“未定义”? . 。
The issue was that console.log
takes its parameters like a printf
statement, and since the string I was logging ( "%A"
) had a special value, it was trying to find the value of the next parameter. 问题是console.log
像printf
语句一样接受其参数,并且由于我正在记录的字符串( "%A"
)具有特殊值,因此它试图查找下一个参数的值。
解决方案:
参考一: https://stackoom.com/question/1oVh/如何在JavaScript正则表达式中访问匹配的组参考二: https://oldbug.net/q/1oVh/How-do-you-access-the-matched-groups-in-a-JavaScript-regular-expression
来源:oschina
链接:https://my.oschina.net/u/4428122/blog/4486081