Python

Python基础(25) - 如何使用正则表达式寻找字符串中的手

2020-03-04  本文已影响0人  xianling_he

Search方法的使用

Match & Search之间的区别是什么

1.Match是用于匹配字符串

import re
m1 = re.match('.*python','I get the python')
print(m1)

2.Search是用于搜素字符串

import re
m2 = re.search('.*python','I get the python')
print(m2)
hexianling.png

假如一个字符串中含有11位的手机号,请问正则表达式如何找到第一次出现手机好的位置,并输出显示

s= 'my phone number is 12134565433'
m = re.search('1\d{10}',s)
print(m)
hexianling.png
s= 'my phone number is 12134565433'
m = re.search('1\d{10}',s)
print(m)

print(m.start()) #开始索引
print(m.end()) #结束索引
hexianling.png

总结

search函数是用于通过正则表达式搜索字符串中第一个符合条件的子字符串,如果没有匹配的子字符串,则返回结果None
如果有符合条件的子字符串,则返回其值,并且可以使用start,end搜索出开始索引,结束索引

加油 2020-3-4

上一篇 下一篇

猜你喜欢

热点阅读