繁体   English   中英

带有 OR 运算符的正则表达式未捕获“双重”匹配

[英]Regex with OR operator not catching "double" matches

使用 PHP 的preg_match_all我有以下问题。

示例字符串:

last_name, first_name
bjorge, philip
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie

正则表达式:

/\bcredit\b|\bcredit note\b|\bfreddie\b/

当前结果:

array(1
  0 =>  array(2
    0   =>  credit
    1   =>  freddie
  )
)

预期结果:

array(1
  0 =>  array(3
    0   =>  credit
    1   =>  credit note
    2   =>  freddie
  )
)

https://www.phpliveregex.com/p/GeW#tab-preg-match-all

可能是一个非常常见的问题,但我无法找到解决方案。

您不能重新访问相同的 position 两次以匹配相同的字符串。

您可以做的是将它们与捕获组放在一个前瞻中,并使credit部分成为可选

$re = '/\b(?=((?:credit )?note|freddie)\b)/';
$str = 'last_name, first_name
bjorge, philip
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie';

preg_match_all($re, $str, $matches);
var_dump($matches[1]);

Output

array(3) {
  [0]=>
  string(11) "credit note"
  [1]=>
  string(4) "note"
  [2]=>
  string(7) "freddie"
}
last_name, first_name
bjorge, philip
credit <-----  ;)
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie

改变输入。

正则表达式将匹配一次,因此根据您的结果,您需要考虑“贷方票据”包含“信用”。 如果您在 php 工作,可以使用 preg_quote()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM