英文:
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|)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论