Search code examples
regexpcre

How to match an optional string at the beginning?


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 |

Should Match

x (A) should match A
(B) should match B

Should Not Match

should not match (Z)
x should (A) not match

Solution

  • Simply place the x and the space character in a non-capturing group and make it optional by using the ? quantifier:

    ^(?:x )?\(([A-Z])\)
    

    Here's a demo.

    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.