锚点
Coddy Python 正则表达式 课程的第 12 课,共 28 课。
锚点是正则表达式中的特殊字符,用于匹配位置,而不是实际字符。最常见的两个锚点是 ^ 和 $。
<strong>^</strong>:匹配字符串的开头。<strong>$</strong>:匹配字符串的结尾。
import re
text = "Hello, world!"
pattern_start = r"^Hello"
pattern_end = r"world!$"
match_start = re.search(pattern_start, text)
match_end = re.search(pattern_end, text)
if match_start:
print("Start anchor match found:", match_start.group()) # 输出:Start anchor match found: Hello
else:
print("No start anchor match found")
if match_end:
print("End anchor match found:", match_end.group()) # 输出:End anchor match found: world!
else:
print("No end anchor match found")在上面的示例中,模式 ^Hello 会匹配字符串开头的 "Hello",而模式 world!$ 会匹配字符串结尾的 "world!"。
挑战
简单编写一个名为 find_lines_starting_with 的函数,它接收一个字符串列表和一个单词作为输入,并返回以给定单词开头的字符串列表。
亲手试试
import re
def find_lines_starting_with(lines, word):
# 在这里编写代码Python 正则表达式中的所有课
自己练习: Python 在线编译器
用你自己的文本测试正则: 正则表达式测试器