如何在不创建分组的情况下表达“匹配一个词或另一个词”?

huangapple go评论85阅读模式
英文:

How to express "match a word or another" without creating a group?

问题

我正在尝试使用正则表达式匹配这种字符串:

{{location|
{{location dec|
{{location other|

所以我想到了这个正则表达式:

{{location( dec| other|)

这个正则表达式可以正常工作,但是它在( dec|)处创建了一个分组,而我并不需要。有没有办法做到同样的事情,但不创建分组呢?

英文:

I'm trying to match this kind of strings with a regular expression:

{{location|
{{location dec|
{{location other|

so I came up with this regular expression:

{{location( dec| other|)

which works fine, however it's creating a group at ( dec|), which I don't need. Is there any way to do the same thing but without creating a group?

答案1

得分: 4

你需要一个组,但是你可以在开括号后面添加?:来使其成为一个非捕获组:

(?: dec| other|)

非捕获意味着该组仅存在于表达式中;无法进行反向引用,并且组编号不受影响。

英文:

You need a group, but you can make it a non-capturing group by adding ?: after the opening bracket:

(?: dec| other|)

Non-capturing means the group exists just for the expression; no back references are possible and group numbering is unaffected.

答案2

得分: 2

你可以使用?:来防止创建分组,所以请尝试一下:

{{location(?: dec| other|)

英文:

You can use ?: to prevent group creation so please give a try to:

{{location(?: dec| other|)

huangapple
  • 本文由 发表于 2015年4月13日 01:00:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/29592050.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定