使正则表达式的尾部部分可选
我正在使用以下正则表达式来匹配下面的字符串,到目前为止一切顺利。现在,我如何使 BAZ
的内容成为可选,以便它与 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' =>
);
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' =>
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您只想将整个内容包装在非捕获组中并添加
?
运算符。请注意,这捕获了 BAZ,其后没有括号。如果您正在寻找 BAZ (),请使用:
Sounds like you just want to wrap the whole thing in a non-capturing group and add a
?
operator.Note that this captures BAZ with no parentheses after it. If you're looking for BAZ () instead, use this:
要使某些内容可选,您可以将其放入非捕获组
(?: ... )
中,然后在该组后面放置一个问号。问号是量词,意思是“零或一”。换句话说,将 this: 更改
为这样:
这样整个表达式就变成了:
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:
to this:
So the entire expression becomes: