如何使用多行负后视来匹配字符串?

How to match strings using negative lookbehind with multilines?

我试图创建 some examples 以更好地理解 PRCE 的正则表达式断言。

//(?<=) - positive lookbehind
$string = "dra Julia \ndr Marcos \ndr Mateus \ndra Ana";
$regex  = "/(?<=dra\s)(\w+)/im";
preg_match_all($regex, $string, $matches);
var_dump($matches);

返回“Julia”和“Ana”运行良好 但否定版本:

$regex  = "/(?<!^dra\s)\b\w+\b$/im";
preg_match_all($regex, $string, $matches);
var_dump($matches);

Returns空:( 我期待“Marcos”和“Mateus”就像使用 regex101.

我怎样才能达到这个结果?

名字后面有一个space。请注意,\s 也匹配换行符,\h 匹配水平白色space 字符。

您可以将模式更新为:

(?<!^dra\h)\b\w+\b\h*$

Regex demo

要获得没有结尾 space 的名称,您可以使用 a lookahead or a capturing group