#正则表达式之 match以及分组
import re
#无分组
origin = "hello alex bcd alex lge alex avd 19"
r = re.match ("h\w+",origin)
print(r.group()) #获取匹配到的所有结果
print(r.groups()) #获取模型中匹配到的分组结果
print(r.groupdict()) #获取模型中匹配的分组结果
hello
()
{}
#有分组
#为何要有分组? 提取匹配成功的制定内容(先欧赔成功全部正则,在再匹配成功的局部内容提取出来)
origin = "hello alex bcd alex lge alex avd 19"
r = re.match("(?P<n1>h)(?P<n2>\w+)",origin)
print(r.group()) #获取匹配到的所有结果
print(r.groups()) #获取模型中匹配到的分组结果
print(r.groupdict()) #获取模型中匹配到的分组中所有执行了key的组
hello
('h', 'ello')
{'n1': 'h', 'n2': 'ello'}
--------------------------------------------------------------------------------------------------------------
#正则表达式之findall
import re
origin = "hello alex alex bcd abcd lge acd 19"
r = re.findall("(a)(\w+)(x)",origin)
print(r)
[("a","le","x"),("a","le","x")]
a = "alex"
n = re.findall("(\w)(\w)(\w)(\w)",a)
print(n)
[('a', 'l', 'e', 'x')]
n = re.findall("(\w)*",a)
print(n)
['x', '']
n =re.findall("","abcd")
print(n)
['', '', '', '', '']
-----------------------------------------
#正则表达式之sub,subn
import re
origin = "1fsdfsd234sdfsdfdfgrm456gfhkbss34"
new_str = re.sub("\d+","kkk",origin)
print(new_str)
kkkfsdfsdkkksdfsdfdfgrmkkkgfhkbsskkk
origin ="1fdfsffsd234gdsgertsg456gsfsf34"
new_str,count = re.subn("\d+","kkk",origin)
print(new_str,count)
('kkkfdfsffsdkkkgdsgertsgkkkgsfsfkkk', 4)