前瞻断言
Coddy Python 正则表达式 课程的第 20 课,共 28 课。
前瞻断言是一种断言,只有在一组字符后面跟着(正向前瞻)或不跟着(负向前瞻)特定模式时,才允许匹配这组字符。前瞻断言不会消耗字符串中的字符,只会断言是否可能匹配。
- 正向前瞻
<strong>(?=...)</strong>:只有在一组字符后面跟着特定模式时,才匹配这组字符。 - 负向前瞻
<strong>(?!...)</strong>:只有在一组字符后面不跟着特定模式时,才匹配这组字符。
import re
text = "foo1 foo2 foo3 foo"
pattern_positive = r"foo(?=\d)"
pattern_negative = r"foo(?!\d)"
matches_positive = re.findall(pattern_positive, text)
matches_negative = re.findall(pattern_negative, text)
print("Matches with positive lookahead:", matches_positive) # 输出:['foo', 'foo', 'foo']
print("Matches with negative lookahead:", matches_negative) # 输出:['foo']在上面的示例中,模式 foo(?=\d) 只有在 "foo" 后面跟着一个数字时才会匹配 "foo",而模式 foo(?!\d) 只有在 "foo" 后面不跟着一个数字时才会匹配 "foo"。
挑战
简单编写一个名为 find_numbers_followed_by_words 的函数,它接收一个文本字符串作为输入,并返回后面跟着单词的数字列表。
亲手试试
import re
def find_numbers_followed_by_words(text):
# 在这里编写代码Python 正则表达式中的所有课
自己练习: Python 在线编译器
用你自己的文本测试正则: 正则表达式测试器