我试图在文本中捕获仅在匹配后没有特定字符时才匹配的组,在这种情况下,左括号“(”表示“函数/方法”而不是“属性”的开始。
这看起来很简单,所以我试过:
TEXT
$this->willMatch but $this->willNot()
RESULT
RegExp pattern: \$this->[a-zA-Z0-9\_]+(?<!\()
Expected: $this->willMatch
Actual: $this->willMatch, $this->willNot
RegExp pattern: \$this->[a-zA-Z0-9\_]+[^\(]
Expected: $this->willMatch
Actual: $this->willMatch, $this->willNot
RegExp pattern: \$this->[a-zA-Z0-9]+(?!\()
Expected: $this->willMatch
Actual: $this->willMatch, $this->willNo
Run Code Online (Sandbox Code Playgroud)
我的直觉是我需要添加 ^ 和 $ 但这不适用于文本中的多次出现。
很想认识可以解决这个问题的 RegExp 向导!
第四只鸟的答案绝对有效,并且也得到了很好的解释。
作为使用词边界的替代方法,可以使用所有格量词,即++关闭回溯,从而进一步提高效率。
\$this->\w++(?!\()
Run Code Online (Sandbox Code Playgroud)
请注意这里使用的\w而不是等效的[a-zA-Z0-9_]。
与贪婪量词一样,所有格量词尽可能多地重复标记。与贪婪量词不同,它不会在引擎回溯时放弃匹配。
该(?<!\()永远是真实的字符类不匹配(
请注意,您不必逃避 \_
您可以在字符类之后使用单词边界来防止回溯,并将负向后向转变为负向前向(?!\()以断言不(直接向右。
\$this->[a-zA-Z0-9_]+\b(?!\()
Run Code Online (Sandbox Code Playgroud)