2

I was reading the Groovy tutorial and they talk about how you can create non-matching groups by leading the group off with ?:. This way the group will not come up on the matcher. What I dont understand is why you would want to explicitly say do not match this group. Wouldnt it be simpler to just not put it into a group?

4

2 回答 2

3

?:用于分组,但当您不想捕获它们时。这对于代码的简洁很有用,有时也是必要的。这有助于在匹配后不存储我们随后不需要的东西,从而节省空间。

它们也主要与|运算符一起使用。

交替运算符在所有正则表达式运算符中的优先级最低。也就是说,它告诉正则表达式引擎匹配竖线左侧的所有内容或竖线右侧的所有内容。如果要限制交替的范围,则需要使用括号进行分组。(http://www.regular-expressions.info/alternation.html)。

在这种情况下,您不能不将它们放在一个组中就离开它们。您将需要在许多常用的正则表达式中使用交替运算符,例如电子邮件、url 等。希望对您有所帮助。

/(?:http|ftp):\/\/([^\/\r\n]+)(\/[^\r\n]*)?/g是 JavaScript 中的示例 URL 正则表达式,它需要交替运算符并需要分组。如果不分组匹配将仅http适用于所有 http url。

于 2013-11-01T03:27:34.863 回答
1
于 2013-11-01T04:10:25.747 回答