Menu
CoddyTech

量词

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

量词可以指定正则表达式模式中的某个字符或一组字符可以重复多少次。最常用的量词是 *、+ 和 ?。

  • <strong>*</strong>:匹配前一个元素重复 0 次或多次。
  • <strong>+</strong>:匹配前一个元素重复 1 次或多次。
  • <strong>?</strong>:匹配前一个元素重复 0 次或 1 次。
import re

text = "The rain in Spain stays mainly in the plain."
pattern_star = r"Sp.*n"
pattern_plus = r"Sp.+n"
pattern_question = r"Sp.?n"

matches_star = re.findall(pattern_star, text)
matches_plus = re.findall(pattern_plus, text)
matches_question = re.findall(pattern_question, text)

print("Matches for '*':", matches_star)  # 输出:['Spain stays mainly in the plain']
print("Matches for '+':", matches_plus)  # 输出:['Spain stays mainly in the plain']
print("Matches for '?':", matches_question)  # 输出:['Span']

在上面的示例中,模式 Sp.*n 匹配 “Spain stays mainly in the plain”,因为 .* 会匹配任意字符(换行符除外)0 次或多次。模式 Sp.+n 匹配 “Spain stays mainly in the plain”,因为 .+ 会匹配任意字符 1 次或多次。模式 Sp.?n 匹配 “Span”,因为 .? 会匹配任意字符 0 次或 1 次。

challenge icon

挑战

简单

编写一个名为 find_repeated_words 的函数,它接收一个文本字符串作为输入,并返回一个包含字母 "a" 零次或多次的单词列表。

亲手试试

import re

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

Python 正则表达式中的所有课

自己练习: Python 在线编译器

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