text = "Contact us at support@example.com or sales@company.com." # 匹配 "@" 后的部分 pattern = r'(?<=@)\w+' matches = re.findall(pattern, text) print(matches) # 输出:['example', 'company']
负向后向断言(Negative
Lookbehind)
匹配某个位置前面不紧跟特定内容。
语法:
1
(?<!pattern)
示例:
1 2 3 4 5 6 7
import re
text = "Contact us at support@example.com or sales@company.com." # 匹配前面不是 @ 的单词 pattern = r'(?<!@)\b\w+' matches = re.findall(pattern, text) print(matches) # 输出:['Contact', 'us', 'at', 'support', 'or', 'sales']
3. 后向引用
后向引用是指在正则表达式中引用之前捕获的内容,可以用 \1,
\2, 等等表示。
示例:
匹配文本中的重复单词:
1 2 3 4 5 6 7
import re
text = "I saw a dog and a cat, but I didn't see the dog dog." # 匹配重复单词 pattern = r'\b(\w+)\b\s+\1\b' matches = re.findall(pattern, text) print(matches) # 输出:['dog']
4. 平衡组
平衡组主要用于匹配嵌套结构(例如括号对等结构)。Python 的标准库
re
不直接支持平衡组操作,但可以通过复杂的逻辑来实现。例如,使用
pyparsing 或 regex 模块可以更好地处理。