Menu
CoddyTech

重复

Coddy Python 正则表达式 课程的第 15 课,共 28 课。

花括号 {} 量词可让你指定前面元素重复的确切次数,或重复次数的范围。

  • <strong>{n}</strong>:匹配恰好重复 n 次。
  • <strong>{n,}</strong>:匹配重复 n 次或更多次。
  • <strong>{n,m}</strong>:匹配重复 n 到 m 次。
import re

text = "The numbers are 1234, 5678, 12345, and 678901."
pattern_exact = r"\b\d{4}\b"
pattern_range = r"\b\d{4,5}\b"

matches_exact = re.findall(pattern_exact, text)
matches_range = re.findall(pattern_range, text)

print("Matches for '{4}':", matches_exact)  # 输出:['1234', '5678']
print("Matches for '{4,5}':", matches_range)  # 输出:['1234', '5678', '12345']

在上面的示例中,模式 \b\d{4}\b 会匹配任意四位数,模式 \b\d{4,5}\b 会匹配任意四位数或五位数。

challenge icon

挑战

简单

编写一个名为 find_four_letter_words 的函数,它接收一个文本字符串作为输入,并返回所有四字母单词组成的列表。

亲手试试

import re

def find_four_letter_words(text):
    # 在这里编写代码

Python 正则表达式中的所有课

自己练习: Python 在线编译器

用你自己的文本测试正则: 正则表达式测试器