我想使用正则表达式匹配字符串的一部分,然后访问带括号的子字符串:

var myString=“something format_abc”;//我要“abc”var arr=/(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString);控制台日志(arr);//打印:[“format_abc”,“abc”]。。到现在为止,一直都还不错。控制台日志(arr[1]);//打印:未定义(???)控制台日志(arr[0]);//打印:format_undefined(!!!)

我做错了什么?


我发现上面的正则表达式代码没有任何问题:我测试的实际字符串是这样的:

"date format_%A"

报告“%A”未定义似乎是一种非常奇怪的行为,但它与这个问题没有直接关系,所以我打开了一个新的问题,为什么匹配的子字符串在JavaScript中返回“undefined”?。


问题是console.log像printf语句一样接受其参数,因为我记录的字符串(“%a”)有一个特殊值,所以它试图查找下一个参数的值。


当前回答

不需要调用exec方法!您可以直接对字符串使用“match”方法。别忘了括号。

var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...

位置0有一个包含所有结果的字符串。位置1的第一个匹配项用括号表示,位置2的第二个匹配项在括号中隔离。嵌套的括号很棘手,所以要小心!

其他回答

使用代码:

console.log(arr[1]);  // prints: abc
console.log(arr[0]);  // prints:  format_abc

编辑:Safari 3,如果重要的话。

即使我同意PhiLo的正则表达式应该是:

/\bformat_(.*?)\b/

(当然,我不确定,因为我不知道正则表达式的上下文。)

只有当你有一对括号时才实用的一行:

while ( ( match = myRegex.exec( myStr ) ) && matches.push( match[1] ) ) {};

单线解决方案:

const matches = (text,regex) => [...text.matchAll(regex)].map(([match])=>match)

因此您可以使用这种方式(必须使用/g):

matches("something format_abc", /(?:^|\s)format_(.*?)(?:\s|$)/g)

结果:

[" format_abc"]

获取所有组事件

设m=[],s=“something format_abc format_def format_ghi”;s.replace(/(?:^|\s)format_(.*?)(?:\s|$)/g,(x,y)=>m.push(y));控制台日志(m);