常见闭包操作符
*
:匹配前一个字符零次或多次。例如,a*
可以匹配空字符串、a
、aa
、aaa
等。
+
:匹配前一个字符一次或多次。例如,a+
可以匹配 a
、aa
、aaa
等,但不能匹配空字符串。
?
:匹配前一个字符零次或一次。例如,a?
可以匹配空字符串或 a
。
使用闭包操作符进行频数匹配及原理
import re
# 使用 * 进行频数匹配
text1 = "aaaaab"
pattern1 = "a*b"
match1 = re.search(pattern1, text1)
if match1:
print(f"使用 * 匹配成功,匹配内容: {match1.group()}")
# 原理:* 允许前面的字符 'a' 出现零次或多次,然后匹配字符 'b'。在这个例子中,它会尽可能多地匹配 'a',直到遇到 'b'。
# 使用 + 进行频数匹配
text2 = "aaaaab"
pattern2 = "a+b"
match2 = re.search(pattern2, text2)
if match2:
print(f"使用 + 匹配成功,匹配内容: {match2.group()}")
# 原理:+ 要求前面的字符 'a' 至少出现一次,然后匹配字符 'b'。所以它会从字符串开头一直匹配 'a',直到遇到 'b'。
# 使用? 进行频数匹配
text3 = "ab"
pattern3 = "a?b"
match3 = re.search(pattern3, text3)
if match3:
print(f"使用? 匹配成功,匹配内容: {match3.group()}")
text4 = "b"
match4 = re.search(pattern3, text4)
if match4:
print(f"使用? 匹配成功,匹配内容: {match4.group()}")
# 原理:? 允许前面的字符 'a' 出现零次或一次,然后匹配字符 'b'。在第一个例子中,'a' 出现一次再匹配 'b';在第二个例子中,'a' 出现零次(即空字符串)然后匹配 'b'。