Reputation: 6250
I'm looking for a regular expression that will simplify what I have no without using an OR regex - |
because I only want one capturing group.
The rules are to match anything at the beginning of the line that is a x
with a space after it and then a single capital letter in ().
Or to match anything that is a capital letter in () at the start of the line.
^\(([A-Z])\)|^x \(([A-Z])\) # works with |
x (A) should match A
(B) should match B
should not match (Z)
x should (A) not match
Upvotes: 0
Views: 176
Reputation: 19641
Simply place the x
and the space character in a non-capturing group and make it optional by using the ?
quantifier:
^(?:x )?\(([A-Z])\)
Alternatively, you can still use the |
operator but have only one capturing group if you use a positive Lookbehind:
(?<=^x |^)\(([A-Z])\)
Demo.
You can even take it a step further and get rid of the capturing group completely and just have the capital letter as the entire match if you wish:
(?<=^x \(|^\()[A-Z](?=\))
Demo.
That would be an overkill though. I'd go with the first solution.
Upvotes: 1