Search code examples
phpregexpattern-matchingtext-extraction

Make trailing portion of a regular expression optional


I'm using the following regex to match the string below, so far so good. Now, how could I make the content of BAZ optional so it matches cases where BAZ ()?

$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST';

preg_match('/FOO (\d+).+BAR (\d+).+BAZ \(\\\\(\w+)\)/i', $str, $match);

$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ () TEST';
$array = array(
    'FOO' => 3,
    'BAR' => 213,
    'BAZ' => 
);

Solution

  • Sounds like you just want to wrap the whole thing in a non-capturing group and add a ? operator.

    /FOO (\d+).+BAR (\d+).+BAZ (?:\(\\\\(\w+)\))?/i
    

    Note that this captures BAZ with no parentheses after it. If you're looking for BAZ () instead, use this:

    /FOO (\d+).+BAR (\d+).+BAZ \((?:\\\\(\w+))?\)/i