$ 匹配结尾字符

定义整个字符串必须以指定字符串结尾

import re
print(re.match('.*d$','2testaabcd')) #字符串必须以d结尾
a=re.match('.*d$','2testaabcd')
print(a.group())
print(re.match('.*c$','2testaabcd'))  #字符串不是以c结尾,返回none
b=re.match('.*c$','2testaabcd')
#注:rP:$,原教程第二个没有添加$,RP自己发现了
c=re.match('.*c$','2testaabc')
print(c.group())


输出:

<re.Match object; span=(0, 10), match='2testaabcd'>
2testaabcd
None
2testaabc

^ 匹配开头字符

定义整个字符串必须以指定字符开头

import re
print(re.match('^2','2stoooabatestas')) #规定必须以2开头,否则none
a=re.match('^2','2stoooabatestas')
print(a.group())
print(re.match('^2s','2stoooabatestas')) #必须以2s开头
b=re.match('^2s','2stoooabatestas')
print(b.group())
c=re.match('^32s','32stoooabatestas')
print(re.match('^2','32stoooabatestas'))
print(c.group())

输出:

<re.Match object; span=(0, 1), match='2'>
2
<re.Match object; span=(0, 2), match='2s'>
2s
None
32s

\b 匹配一个单词的边界

\b:表示字母数字与非字母数字的边界,非字母数字与字母数字的边界。即下面ve的右边不能有字母和数字

import re
print(re.match(r'.*ve\b','ve.2testaabcd'))  #因为在python中\代表转义,所以前面加上r消除转义
a=re.match(r'.*ve\b','ve.2testaabcd')
print(a.group())
print(re.match(r'.*ve\b','ve2testaabcd'))
print(re.match(r'.*ve\b','vep2testaabcd'))#rp:遇到字母或数字不显示

 输出:

<re.Match object; span=(0, 2), match='ve'>
ve
None
None

\B 匹配非单词边界

import re
print(re.match(r'.*ve\B','2testaavebcdve'))  #ve的右边需要有字母或者数字
a=re.match(r'.*ve\B','2testaavebcdve')
print(a.group())
print(re.match(r'.*ve\B','2testaave3bcdve'))
print(re.match(r'.*ve\B','2testaave.3bcdve'))#点
print(re.match(r'.*ve\B','2testaave 3bcdve'))#空格
print(re.match(r'.*ve\B','2testaave*3bcdve'))#星号

 输出:

<re.Match object; span=(0, 9), match='2testaave'>
2testaave
<re.Match object; span=(0, 9), match='2testaave'>
None
None
None

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐