Javascript 正则表达式中的捕获组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6418985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:39:37  来源:igfitidea点击:

capturing group in regex

javascriptregex

提问by Madhur Ahuja

I am exploring capturing groups in Regex and I am getting confused about lack of documentation on it. For ex, can anyone tell me difference between two regex:

我正在探索 Regex 中的捕获组,但我对缺乏有关它的文档感到困惑。例如,谁能告诉我两个正则表达式之间的区别:

/(?:madhur)?/

and

/(madhur)?/

As per me, ? in second suggests matching madhurzero or once in the string.

在我看来,? in second 建议madhur在字符串中匹配零或一次。

How is the first different from second ?

第一个和第二个有什么不同?

回答by alex

The first one won't store the capturing group, e.g. $1will be empty. The ?:prefix makes it a non capturing group. This is usually done for better performance and un-cluttering of back references.

第一个不会存储捕获组,例如$1将是空的。该?:前缀使其成为一个非捕获组。这样做通常是为了更好的性能和整洁的反向引用。

In the second example, the characters in the capturing group will be stored in the backreference $1.

在第二个示例中,捕获组中的字符将存储在反向引用中$1

Further Reading.

进一步阅读

回答by brymck

Here's the most obvious example:

这是最明显的例子:

"madhur".replace(/(madhur)?/, " ahuja");   // returns "madhur ahuja"
"madhur".replace(/(?:madhur)?/, " ahuja"); // returns " ahuja"

Backreferences are stored in order such that the first match can be recalled with $1, the second with $2, etc. If you capture a match (i.e. (...)instead of (?:...)), you can use these, and if you don't then there's nothing special. As another example, consider the following:

反向引用按顺序存储,这样第一个匹配可以用 调用$1,第二$2个匹配用等等。如果您捕获匹配(即(...)代替(?:...)),您可以使用这些,如果您不这样做,则没有什么特别的。作为另一个示例,请考虑以下内容:

/(mad)hur/.exec("madhur");   // returns an array ["madhur", "mad"]
/(?:mad)hur/.exec("madhur"); // returns an array ["madhur"]

回答by AndreKR

It doesn't affect the matching at all.

完全不影响匹配。

It tells the regex engine

它告诉正则表达式引擎

  • not to store the group contents for use (as $1, $2, ...) by the replace()method
  • not to return it in the return array of the exec()method and
  • not to count it as a backreference (\1, \2, etc.)
  • 不存储组内容的使用(如$ 1,$ 2,...)由replace()方法
  • 不要在方法的返回数组中返回它,exec()并且
  • 不要将其视为反向引用(\1、\2 等)