正则表达式?: ?= ?! 的用法详解

文章目录

  • 1. ?: 用法
  • 2. ?= 用法
  • 3. ?! 用法
  • 4. 总结

    正则表达式中使用的 ?:、?= 和 ?! 是三种不同的正则表达式语法,它们分别代表非捕获组、正向前瞻断言和负向前瞻断言。

    1. ?: 用法

    (?:...) 是一种非捕获组(non-capturing group)的语法。它用于将一部分正则表达式括在一起,但不将该部分作为单独的捕获组。这意味着即使匹配了这部分表达式,也不会在结果中创建新的捕获组。

    正则表达式中的捕获组(capture group)是使用圆括号 () 包围的一部分表达式。这些捕获组在匹配到的字符串中标记了特定的部分,并将其保存起来以供稍后使用。

    如果还不清楚什么是捕获组,下面给一个例子就清楚了:

    import re
    pattern = r'a(.*)test'
    text = 'This is a good test.'
    match = re.search(pattern, text)
    if match:
        print("Found word:", match.groups())
    # 输出
    # Found word: (' good ',)
    

    在这个示例中,(.*) 是一个捕获组,用于将a 和 test 中间的字符提取出来。

    知道了捕获组,那么非捕获组也能猜出来了。有时你可能只想将表达式括在一起,但不想保存匹配结果。在这种情况下,可以使用非捕获组 (?: ...)

    示例:

    import re
    pattern = r'(?:abc)def'
    text = 'abcdef'
    match = re.search(pattern, text)
    if match:
        print("Match found")
    

    在这个示例中,(?:abc) 是一个非捕获组,它将 abc 与 def 组合在一起进行匹配,但不会作为单独的捕获组。

    2. ?= 用法

    ?= 是正向前瞻断言(positive lookahead assertion)。它用于匹配某个子表达式后的位置,但不包含匹配到的子表达式在最终的结果中。前瞻断言用来确保某一部分的匹配被后续某一部分的条件匹配。

    示例:

    import re
    pattern = r'abc(?=def)'
    text = '.x abcdef123'
    text2 = '.x abc1def123'
    match = re.search(pattern, text)
    if match:
        print("Match found:", match.group())
    # 输出
    # Match found: abc
    match = re.search(pattern, text2)
    if not match:
        print("Match not found")
    # 输出
    # Match not found
    

    在这个示例中,abc(?=def) 使用了正向前瞻断言。它将匹配 abc 后面跟着 def 的部分。在 abcdef 中,它匹配了 abc,因为 abc 后面是 def。

    3. ?! 用法

    ?! 是负向前瞻断言(negative lookahead assertion)。它用于确保某个子表达式不匹配之后的位置,而不包含匹配到的子表达式在最终的结果中。

    用法示例:

    import re
    pattern = r'abc(?!def)'
    text = 'abcxyz'
    text2 = 'abcdef'
    match = re.search(pattern, text)
    if match:
        print("Match found:", match.group())
    # 输出
    # Match found: abc
    match = re.search(pattern, text2)
    if not match:
        print("Match not found")
    # 输出
    # Match not found
    

    在这个示例中,abc(?!def) 使用了负向前瞻断言。它将匹配 abc 后面不跟着 def 的部分。在 abcxyz 中,它匹配了 abc,因为 abc 后面没有 def。

    4. 总结

    • (?:...) 是非捕获组,不会捕获组内的匹配结果。
    • ?= 是正向前瞻断言,确保匹配后的位置满足条件。
    • ?! 是负向前瞻断言,确保匹配后的位置不满足条件。