Can I use an OR in regex without capturing what's enclosed?

爷,独闯天下 提交于 2019-11-27 00:07:37

问题


I'm using rubular.com to build my regex, and their documentation describes the following:

(...)   Capture everything enclosed
(a|b)   a or b

How can I use an OR expression without capturing what's in it? For example, say I want to capture either "ac" or "bc". I can't use the regex

(a|b)(c)

right? Since then I capture either "a" or "b" in one group and "c" in another, not the same. I know I can filter through the captured results, but that seems like more work...

Am I missing something obvious? I'm using this in Java, if that is pertinent.


回答1:


Depending on the regular expression implementation you can use so called non-capturing groups with the syntax (?:…):

((?:a|b)c)

Here (?:a|b) is a group but you cannot reference its match. So you can only reference the match of ((?:a|b)c) that is either ac or bc.




回答2:


If your implementation has it, then you can use non-capturing parentheses:

(?:a|b)



回答3:


Even rubular doesn't make you use parentheses and the precedence of | is low. For example a|bc does not match ccc



来源:https://stackoverflow.com/questions/3378773/can-i-use-an-or-in-regex-without-capturing-whats-enclosed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!