正则表达式:(?=(\d+))\w+\1
字串:456x56
你好,
我不明白这个正则表达式如何匹配字符串“456x56”中的“56x56”。
但是,regexp匹配56x56。
最佳答案
正如您所说的,您不必 anchor 定正则表达式。另一个问题是\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>
关于regex - 正则表达式匹配字符串-正向提前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8769998/