regex - 正则表达式匹配字符串-正向提前

标签 regex lookahead regex-lookarounds

正则表达式:(?=(\d+))\w+\1字串:456x56
你好,

我不明白这个正则表达式如何匹配字符串“456x56”中的“56x56”。

  • 环顾四周(?=(\d +))捕获456并放入\1中,表示(\d +)
  • 单词字符\w +与整个字符串匹配(“456x56”)
  • \1,即456,后跟\w +
  • 在回溯字符串之后,它不应该找到匹配项,因为没有以单词字符开头的“456”

  • 但是,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/

    相关文章:

    c# - 如何匹配<>之间的字符串?

    android - 在android中使用sqlite的正则表达式

    php - JavaScript 和 PHP 之间前瞻断言的惰性差异

    php - 左侧的正则表达式不贪婪(即,两侧可能的最窄匹配)

    正则表达式匹配不以模式结尾的字符串?

    python - 使用正则表达式匹配不以特定字母开头的单词

    Javascript RegEx 正面前瞻未按预期工作

    python - 文件读取和RE解析

    mysql - 在 Group by Clause 中使用正则表达式

    javascript - 如何在 JavaScript 中生成单词中字符替换的所有可能组合?