欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

正则表达式 ? :? = ?!用法说明-3!使用说明

最编程 2024-04-20 10:55:12
...

?! 是负向前瞻断言(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

推荐阅读