php regex match pattern
Im 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' =>
);
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
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
精彩评论