加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式非捕获javascript中的组

发布时间:2020-12-14 06:23:51 所属栏目:百科 来源:网络整理
导读:我的正则表达式和 javascript上有点生疏.我有以下字符串var: var subject = "javascript:loadNewsItemWithIndex(5,null);"; 我想用正则表达式提取5.这是我的正则表达式: /(?:loadNewsItemWithIndex()[0-9]+/) 应用如下: subject.match(/(?:loadNewsItemW
我的正则表达式和 javascript上有点生疏.我有以下字符串var:
var subject = "javascript:loadNewsItemWithIndex(5,null);";

我想用正则表达式提取5.这是我的正则表达式:

/(?:loadNewsItemWithIndex()[0-9]+/)

应用如下:

subject.match(/(?:loadNewsItemWithIndex()[0-9]+/)

结果是:

loadNewsItemWithIndex(5

什么是最简洁,最可读的方式来提取5作为一个班轮?是否可以通过排除loadNewsItemWithIndex(来自匹配而不是匹配5作为子组)来做到这一点?

String.match的返回值是一个匹配数组,因此您可以在数字部分周围放置括号,然后只检索该特定匹配索引(其中第一个匹配是整个匹配结果,后续条目是每个捕获组):
var 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读