Sur*_*esh 6 regex lookahead regex-lookarounds
正则表达式:(?=(\d+))\w+\1
字符串:456x56
嗨,
我没有得到这个概念,这个正则表达式如何匹配字符串"456x56"中的"56x56".
但是正则表达式匹配56x56.
5)正则表达式引擎得出的结论是,如果从4开始搜索它就找不到匹配项,因此它会跳过一个字符并再次搜索.这一次,它捕获两个数字\1
并最终匹配56x56
如果您只想匹配整个字符串,请使用 ^(?=(\d+))\w+\1$
^ matches beginning of string
$ matches end of string
Run Code Online (Sandbox Code Playgroud)
正如已经说过的,你没有锚定你的正则表达式.另一个问题是\w
也匹配数字...现在看一下正则表达式引擎如何与你的输入匹配:
# begin
regex: |(?=(\d+))\w+\1
input: |456x56
# lookahead (first group = '456')
regex: (?=(\d+))|\w+\1
input: |456x56
# \w+
regex: (?=(\d+))\w+|\1
input: 456x56|
# \1 cannot be satisfied: backtrack on \w+
regex: (?=(\d+))\w+|\1
input: 456x5|6
# And again, and again... Until the beginning of the input: \1 cannot match
# Regex engine therefore decides to start from the next character:
regex: |(?=(\d+))\w+\1
input: 4|56x56
# lookahead (first group = '56')
regex: (?=(\d+))|\w+\1
input: 4|56x56
# \w+
regex: (?=(\d+))\w+|\1
input: 456x56|
# \1 cannot be satisfied: backtrack
regex: (?=(\d+))\w+|\1
input: 456x5|6
# \1 cannot be satisfied: backtrack
regex: (?=(\d+))\w+|\1
input: 456x|56
# \1 satified: match
regex: (?=(\d+))\w+\1|
input: 4<56x56>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3521 次 |
最近记录: |