前瞻和后顾是正则表达式中的高级技术,用于匹配某个位置的前面或后面是否满足特定的条件。
前瞻正则表达式(Positive Lookahead):
前瞻用来查看当前位置之后的内容是否满足某个条件,但并不消耗匹配的内容。其语法为 (?=pattern)
,其中 pattern 表示要匹配的条件。
示例:
import re
# 匹配所有以数字结尾的单词
pattern = r'\w+(?=\d)'
text = "apple123 orange456 banana789"
result = re.findall(pattern, text)
print(result) # 输出:['apple', 'orange', 'banana']
后顾正则表达式(Positive Lookbehind):
后顾用来查看当前位置之前的内容是否满足某个条件,但并不消耗匹配的内容。其语法为 (?<=pattern)
,其中 pattern 表示要匹配的条件。
示例:
import re
# 匹配所有以数字开头的单词
pattern = r'(?<=\d)\w+'
text = "123apple 456orange 789banana"
result = re.findall(pattern, text)
print(result) # 输出:['apple', 'orange', 'banana']
以上示例分别使用了前瞻和后顾来匹配字符串中特定位置的内容,而不消耗匹配结果。根据不同的需求,你可以灵活运用前瞻和后顾来构建更复杂的正则表达式。