gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:34:09 25 4
gpt4 key购买 nike

正则表达式:(?=(\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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com