编程语言
首页 > 编程语言> > php – 正则表达式匹配字符串BAR,只要字符串FOO没有出现在它之前

php – 正则表达式匹配字符串BAR,只要字符串FOO没有出现在它之前

作者:互联网

我正在尝试编写一个正则表达式,该正则表达式只包含一个包含BAR的字符串,前面没有FOO.

例如,正则表达式不符合以下条件:

FOO IS BAR

但是WOULD符合这个:

BAZ IS BAR

解决方法:

(?<!FOO.*)BAR

是正确的正则表达式(但它只适用于.NET正则表达式引擎).

(?<!FOO.*)是一个negative lookbehind assertion,断言在当前位置之前不可能匹配任何包含FOO的字符串.

在PHP中,您没有无限的外观.另一种选择

^(?:(?!FOO|BAR).)*BAR

说明:

^     # Start of string
(?:   # Match...
 (?!  # (unless the following can be matched here:
  FOO #  either FOO
 |    #  or
  BAR #  BAR)
 )    # (end of lookahead)
 .    # ... any character.
)*    # Repeat as needed
BAR   # Match BAR

但是,即使这不适用于已弃用的ereg函数.您需要preg函数才能使用lookaround断言.

但我认为有一种方法适用于ereg:

^(FO?|[^FO]|[^O]O)*BAR

说明:

^      # Start of string
(      # Either match:
 FO?   # F or FO
|      # or
 [^FO] # any character except F or O
|      # or
 [^O]O # any non-O character followed by O
)*     # any number of times
BAR    # Then match BAR

但是,如果您的排除字符串比FOO更复杂,这将变得非常复杂…

标签:php,regex,ereg
来源: https://codeday.me/bug/20190725/1535374.html