字符匹配: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)
总结:
-
{0,}=====>*
-
{1,}=====>+
-
{0,1}=====>?
-
{6}=====>重复6次
-
{1,6}=====>重复,1,2,3,4,5,6其中任何一次
-
字符集[],[^]代表非