【问题标题】:Regex: match if group is only once in text正则表达式:如果组在文本中只有一次,则匹配
【发布时间】:2020-11-12 04:03:00
【问题描述】:

如果第二组在所有文本中只匹配一次,我需要匹配。 例如,第 1、4、6 个字符串不应匹配: Regex101

AS "(.+)\.(.+)"

table1.field1 AS "table1.field1",
table2.field2 AS "table2.field2",
table3.field3 AS "table3.field3",
table4.field1 AS "table4.field1",
table4.field1 AS "table5.field5",
table6.field6 AS "table6.field1",

【问题讨论】:

  • 你需要添加额外的逻辑来实现这一点,只有正则表达式是不够的,即使是 CFG 也不够

标签: python regex


【解决方案1】:

您可以只使用原始模式,然后过滤匹配项:

regex = r"\bAS \"(.+)\.(.+)\""
matches = re.findall(regex, test_str, re.MULTILINE)

filtered = [x for x in matches 
            if sum(y[1] == x[1] for y in matches) == 1]

输出:

[('table2', 'field2'), ('table3', 'field3'), ('table5', 'field5')]

Try it online.

【讨论】:

    【解决方案2】:

    您实际上可以使用 PyPi 正则表达式模块做您想做的事情,该模块允许无限宽度的后向模式:

    AS "([^.]+)\.([^.]+)"(?<!AS "[^.]+\.\2"[\s\S]*AS "\1\.\2")(?![\s\S]*AS "[^.]+\.\2")
    

    请参阅regex demo。详情:

    • AS "([^.]+)\.([^.]+)":
      • AS " - AS " 字符串
      • ([^.]+) - 第 1 组:. 以外的任何一个或多个字符
      • \. - 一个 . 字符
      • ([^.]+) - 第 2 组:. 以外的任何一个或多个字符
      • " - 一个 " 字符
    • (?&lt;!AS "[^.]+\.\2"[\s\S]*AS "\1\.\2") - 如果在当前位置的左侧紧邻有
      • AS " - 文字字符串
      • [^.]+ - 除了. 之外的一个或多个字符
      • \. - 一个点
      • \2 - 与第 2 组中的值相同
      • " - 双引号
      • [\s\S]* - 尽可能多的 0 个或更多字符
      • AS "\1\.\2" - AS ",与第 1 组相同,.,与第 2 组相同(这里需要确保我们匹配与上述消费模式部分匹配的字符串部分)
    • (?![\s\S]*AS "[^.]+\.\2") - 如果紧挨当前位置的右侧有任何零个或多个字符,AS ",一个或多个除.,@987654349 之外的字符,则匹配失败@,与第 2 组中的值和 " 相同。

    Python demo:

    import regex
    text = """table1.field1 AS "table1.field1",
    table2.field2 AS "table2.field2",
    table3.field3 AS "table3.field3",
    table4.field1 AS "table4.field1",
    table4.field1 AS "table5.field5",
    table6.field6 AS "table6.field1","""
    rx = r'AS "([^.]+)\.([^.]+)"(?<!AS "[^.]+\.\2"[\s\S]*AS "\1\.\2")(?![\s\S]*AS "[^.]+\.\2")'
    print( regex.findall(rx, text) )
    # => [('table2', 'field2'), ('table3', 'field3'), ('table5', 'field5')]
    

    【讨论】:

      猜你喜欢
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 2022-12-11
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多