Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.


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

(?:a|b)

If your OR alternatives are all single characters - you can just use "character set" operator:

([ab]c)

it will only match ac or bc and it's more readable.


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