shareds
shareds

Reputation: 23

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' => 
);

Upvotes: 2

Views: 295

Answers (2)

Justin Morgan
Justin Morgan

Reputation: 30715

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

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838056

To make something optional you can put it in a non-capturing group (?: ... ) then place a question mark after the group. The question mark is a quantifier that means "zero or one".

In other words, change this:

\\\\(\w+)

to this:

(?:\\\\(\w+))?

So the entire expression becomes:

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

Upvotes: 1

Related Questions