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

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”)有一个特殊值,所以它试图查找下一个参数的值。


当前回答

这里有一个方法可以用来获得n​每个匹配的第个捕获组:

函数getMatches(字符串、正则表达式、索引){索引||(索引=1);//默认为第一个捕获组var matches=[];var匹配;while(match=regex.exec(字符串)){matches.push(match[index]);}返回匹配;}//示例:var myString=“something format_abc something format_def something form_ghi”;var myRegEx=/(?:^|\s)format_(.*?)(?:\s|$)/g;//获取包含每个匹配的第一个捕获组的数组var matches=getMatches(myString,myRegEx,1);//日志结果document.write(matches.length+'找到匹配项:'+JSON.stringify(匹配项))console.log(匹配项);

其他回答

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

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

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

/\bformat_(.*?)\b/

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

函数getMatches(字符串、正则表达式、索引){索引||(索引=1);//默认为第一个捕获组var matches=[];var匹配;while(match=regex.exec(字符串)){matches.push(match[index]);}返回匹配;}//示例:var myString='200卢比记入账户。。。2031年2月12日20:05:49(结算余额66248.77卢比)ATM。免费电话180022334418001024455(上午6点至晚上10点);var myRegEx=/清除bal.+?(\d+\.?\d{2})/gi;//获取包含每个匹配的第一个捕获组的数组var matches=getMatches(myString,myRegEx,1);//日志结果document.write(matches.length+'找到匹配项:'+JSON.stringify(匹配项))console.log(匹配项);

函数getMatches(字符串、正则表达式、索引){索引||(索引=1);//默认为第一个捕获组var matches=[];var匹配;while(match=regex.exec(字符串)){matches.push(match[index]);}返回匹配;}//示例:var myString=“something format_abc something format_def something form_ghi”;var myRegEx=/(?:^|\s)format_(.*?)(?:\s|$)/g;//获取包含每个匹配的第一个捕获组的数组var matches=getMatches(myString,myRegEx,1);//日志结果document.write(matches.length+'找到匹配项:'+JSON.stringify(匹配项))console.log(匹配项);

不需要调用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的第二个匹配项在括号中隔离。嵌套的括号很棘手,所以要小心!

var myString=“something format_abc”;var arr=myString.match(/\bformat_(.*?)\b/);控制台日志(arr[0]+“”+arr[1]);

\b并不完全相同。(它适用于--format_foo/,但不适用于format_a_b)但我想展示一个替代表达式,这很好。当然,比赛电话是最重要的。