1.分组匹配 用()把需要分组的类型括起来,如下
import re
m = re.search("([a-z]+)([0-9]+)","alex123")
print(m.groups()) #用groups() 涉及到分组就用groups
# ('alex', '123')
2.”A“ 表示从头开始匹配,和”^“ match 类似
“” 匹配字符结尾,同$
“d” 相当于数字0-9
import re
m = re.search("([a-z]+)([d]+)","alex123")
print(m.groups())
('alex', '123')
“D” 匹配非数字
import re
m = re.findall("D","alex%467*123")
print(m)
# ['a', 'l', 'e', 'x', '%', '*']
“w” 匹配(a-z A-Z 0-9)
import re
m = re.findall("w","alex%467*123")
print(m)
# ['a', 'l', 'e', 'x', '4', '6', '7', '1', '2', '3']
“W” 匹配非(a-z A-Z 0-9)
import re
m = re.findall("W","alex%467*123")
print(m)
# ['%', '*']
“s” 匹配空白字符
import re
m = re.findall("s","ale
x%46 7*123")
print(m)
# ['
', ' ']
“(?P<name>...)” 分组匹配 分组之间不需要加逗号,加了会报错。
import re
s = "321324199309187654"
m = re.search("(?P<convince>d{3})""(?P<city>d{3})""(?P<year>d{4})""(?P<month>d{4})",s)
print(m.groups())
# ('321', '324', '1993', '0918')
调用groupdict,生成字典。
import re
s = "321324199309187654"
m = re.search("(?P<convince>d{3})""(?P<city>d{3})""(?P<year>d{4})""(?P<month>d{4})",s)
print(m.groups())
print(dir(m))
print(m.groupdict())
# {'convince': '321', 'city': '324', 'year': '1993', 'month': '0918'}