简体   繁体   English

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

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

Using PHP's preg_match_all I have the following problem.使用 PHP 的preg_match_all我有以下问题。

Example string:示例字符串:

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

Regex:正则表达式:

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

Current Result:当前结果:

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

Expected result:预期结果:

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

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

Probably a very common problem, but I was not able to find a solution.可能是一个非常常见的问题,但我无法找到解决方案。

You can not revisit the same position twice to match the same string.您不能重新访问相同的 position 两次以匹配相同的字符串。

What you can do is put them in a lookahead with a capture group and make the credit part optional您可以做的是将它们与捕获组放在一个前瞻中,并使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 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

change the input.改变输入。

regex will match once, so based on your result you need to take into account that "credit note" contains "credit".正则表达式将匹配一次,因此根据您的结果,您需要考虑“贷方票据”包含“信用”。 maybe use preg_quote() if you are working in php.如果您在 php 工作,可以使用 preg_quote()。

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

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