我们可以在正则表达式的开始处使用插入符号(^
),表示必须在被查找文本的开始处进行匹配。类似地,还可以在正则表达式的末尾加上美元符号( $
),表示该字符串必须以这个正则表达式的模式结束。可以同时使用^
和 $
。
正则表达式 ^开启
,匹配以 “开启” 开始的字符串:
begin_with_start = re.compile(r'^开启')
print(begin_with_start.search('开启新的征程'))
print(begin_with_start.search('让我们开启新的征程') == None)
运行结果:
<re.Match object; span=(0, 2), match=‘开启’>
True
正则表达式 \d$
,匹配以数字为结束符的字符串:
end_with_numbers=re.compile(r'\d$')
print(end_with_numbers.search('我所在校区的区号是6'))
print(end_with_numbers.search('我所在校区的区号是六') == None)
运行结果:
<re.Match object; span=(9, 10), match=‘6’>
True
我们可以组合使用插入字符、美元字符,比如希望匹配所有字符都是字母的字符串:
whole_string_is_letter=re.compile(r'^\D+$')
print(whole_string_is_letter.search('world'))
print(whole_string_is_letter.search('Harry Potter'))
print(whole_string_is_letter.search('wor1ld')==None)
运行结果:
<re.Match object; span=(0, 5), match=‘world’>
<re.Match object; span=(0, 12), match=‘Harry Potter’>
True
记住: 插入字符在前,美元字符在后。