(100天2小时第十一天)正则模块 re(2). ^ $ * + ? { }

字符匹配:1.普通字符 2.元字符:. ^ $ * + ? { } [ ] | ( ) \

1. .是一个通配符,一个点代表一个字符

s = re.findall("a...x","adsfaeyuxslg")
print(s)
s = re.findall("a..x","adsxaeyxslg")
print(s)

 

2.^这个代表以什么开头,^a,代表以a开头,a必须是字符串的第一个字母

s = re.findall("^a..x","adsfaeuxslg")
print(s)
s = re.findall("^a..x","adsxfaeyuxslg")
print(s)

  

3.$以什么结束,x$,x必须是字符串的最后一个字母。

s = re.findall("a..x$","adsxaeyxslg")
print(s) #[]
a = re.findall("a..x$","adsxaeyxslgarrx")
print(a)

 

4. * 代表0到无穷次,贪婪匹配,d*,可以是d,dd,ddd,dddd……

s = re.findall("d*","sfdderddddddyuyygdd")
print(s)

 

5. +,alex+ 代表最后一个字母x出现(1到无穷次),贪婪匹配。

+和*的区别:*可以出现0次,字符串没有x,可以输出ale.    +如果字符串中没有x输出空。

s=re.findall("alex+","asdhfalexxx")
print(s)
s=re.findall("alex+","asdhfale")
print(s)
a = re.findall("alex*","asdhfale")
print(a)

 

6. ?代表0到1,如果最后一个出现两次只能输出一个

s = re.findall("alex?","asdhfalex")
print(s)
s = re.findall("alex?","asdhfale")
print(s)
s = re.findall("alex?","asdhfalexx")
print(s)

 

7.{6}代表重复6次,{1,6}代表重复,1,2,3,4,5,6其中任何一次

s = re.findall("alex{5}","asdhfalexxxxxx")
print(s)
s = re.findall("alex{0,5}","asdhfalexx")
print(s)

  

8.字符集[  ]

 #[^]字符集中^表示非;该例表示匹配只要不是里面的即可
ret=re.findall('a[bc]d','abd')#从中括号中选
print(ret)
ret=re.findall('[a-z]','acd')
print(ret)
ret=re.findall('[1-5]','45dha3')#包括5
print(ret)
ret=re.findall('[^ab]','45bdha3') #[^]字符集中^表示非;该例表示匹配只要不是a  b即可
print(ret)
ret=re.findall('[\d]','45bdha3')#\d 匹配任何十进制数;它相当于类 [0-9]。
print(ret)

 

总结:

  1. {0,}=====>*

  2. {1,}=====>+

  3. {0,1}=====>?

  4. {6}=====>重复6次

  5. {1,6}=====>重复,1,2,3,4,5,6其中任何一次

  6. 字符集[],[^]代表非

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值