javascript中的正则表达式非捕获组 [英] Regex non capturing groups in javascript

查看:50
本文介绍了javascript中的正则表达式非捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的正则表达式和javascript有点生疏.我有以下字符串var:

I'm a bit rusty on my regex and javascript. I have the following string var:

var subject = "javascript:loadNewsItemWithIndex(5, null);";

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

I want to extract 5 using a regex. This is my regex:

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

应用如下:

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

结果是:

loadNewsItemWithIndex(5

5 提取为单线的最干净,最易读的方法是什么?是否可以通过从匹配项中排除 loadNewsItemWithIndex(而不是将 5 作为子组进行匹配来做到这一点?

What is cleanest, most readable way to extract 5 as a one-liner? Is it possible to do this by excluding loadNewsItemWithIndex( from the match rather than matching 5 as a sub group?

推荐答案

String.match 的返回值是一个匹配数组,因此您可以在数字部分加上括号并直接将其取回特定的匹配索引(其中第一个匹配是整个匹配结果,而随后的条目是针对每个捕获组的):

The return value from String.match is an array of matches, so you can put parentheses around the number part and just retrieve that particular match index (where the first match is the entire matched result, and subsequent entries are for each capture group):

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对非捕获匹配的工作原理进行了更正.

Thanks @Alan for the correction on how non-capturing matches work.

实际上,它运行良好.在内匹配的文本仍使用非捕获组,与匹配的文本相同在任何团体之外.捕获组就像非捕获组具有额外的功能:除了分组以外,它还允许您提取与整体匹配无关的所有匹配项.

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.

这篇关于javascript中的正则表达式非捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆