我发现这个关于正则表达式的优秀教程,虽然我直观地理解"贪婪","不情愿"和"占有欲"量词的作用,但我的理解似乎存在严重漏洞.
具体来说,在以下示例中:
Enter your regex: .*foo // greedy quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfooxxxxxxfoo" starting at index 0 and ending at index 13.
Enter your regex: .*?foo // reluctant quantifier
Enter input string to search: xfooxxxxxxfoo
I found the text "xfoo" starting at index 0 and ending at index 4.
I found the text "xxxxxxfoo" starting at index 4 and ending at index 13.
Enter your regex: .*+foo // possessive quantifier
Enter …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个正则表达式,其中包含所有具有任意数量单词但不能后跟 : 的字符串,如果匹配则忽略匹配项。我决定对它进行负面展望。
/([a-zA-Z]+)(?!:)/gm
string: lame:joker
Run Code Online (Sandbox Code Playgroud)
因为我使用的是一个字符范围,它一次匹配一个字符,并且只忽略 : 之前的最后一个字符。在这种情况下,我如何忽略整个比赛?
regex101 链接:https ://regex101.com/r/DlEmC9/1
我试图在文本中捕获仅在匹配后没有特定字符时才匹配的组,在这种情况下,左括号“(”表示“函数/方法”而不是“属性”的开始。
这看起来很简单,所以我试过:
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 向导!