后顾断言
Coddy Python 正则表达式 课程的第 21 课,共 28 课。
后行断言用于匹配一组字符,前提是它们前面有(正向后行断言)或没有(负向后行断言)特定模式。和先行断言一样,后行断言不会消耗字符串中的字符。
- 正向后行断言
<strong>(?<=...)</strong>:仅当一组字符前面有特定模式时,才匹配这组字符。 - 负向后行断言
<strong>(?<!...)</strong>:仅当一组字符前面没有特定模式时,才匹配这组字符。
import re
text = "1foo 2foo 3foo foo"
pattern_positive = r"(?<=\d)foo"
pattern_negative = r"(?<!\d)foo"
matches_positive = re.findall(pattern_positive, text)
matches_negative = re.findall(pattern_negative, text)
print("Matches with positive lookbehind:", matches_positive) # 输出:['foo']
print("Matches with negative lookbehind:", matches_negative) # 输出:['foo', 'foo', 'foo']在上面的示例中,模式 (?<=\d)foo 仅当 "foo" 前面有数字时才匹配它,而模式 (?<!\d)foo 仅当 "foo" 前面没有数字时才匹配它。
挑战
简单编写一个名为 find_words_preceded_by_numbers 的函数,它接受一个文本字符串作为输入,并返回一个前面有数字的单词列表。
亲手试试
import re
def find_words_preceded_by_numbers(text):
# 在这里编写代码Python 正则表达式中的所有课
自己练习: Python 在线编译器
用你自己的文本测试正则: 正则表达式测试器