我的正则表达式和
javascript上有点生疏.我有以下字符串var:
var subject = "javascript:loadNewsItemWithIndex(5,null);";
我想用正则表达式提取5.这是我的正则表达式:
/(?:loadNewsItemWithIndex\()[0-9]+/)
应用如下:
subject.match(/(?:loadNewsItemWithIndex\()[0-9]+/)
结果是:
loadNewsItemWithIndex(5
什么是最简洁,最可读的方式来提取5作为一个班轮?是否可以通过排除loadNewsItemWithIndex(来自匹配而不是匹配5作为子组)来做到这一点?
String.match的返回值是一个匹配数组,因此您可以在数字部分周围放置括号,然后只检索该特定匹配索引(其中第一个匹配是整个匹配结果,后续条目是每个捕获组):
原文链接:https://www.f2er.com/regex/356839.htmlvar subject = "javascript:loadNewsItemWithIndex(5,null);"; var result = subject.match(/loadNewsItemWithIndex\(([0-9]+)/); // ^ ^ added parens document.writeln(result[1]); // ^ retrieve second match (1 in 0-based indexing)
示例代码:http://jsfiddle.net/LT62w/
编辑:感谢@Alan纠正非捕获匹配的工作方式.
Actually,it’s working perfectly. Text that’s matched inside a non-capturing group is still consumed,the same as text that’s matched outside of any group. A capturing group is like a non-capturing group with extra functionality: in addition to grouping,it allows you to extract whatever it matches independently of the overall match.