正则表达式二

#search匹配原则:浏览全部,匹配第一个出现的字符串。
test = (re.search('abc','abcababc')).group()
print(test)
#abc
print(re.search('a(\d+?)','a123').group())
#a1
print(re.search('a(\d*?)','a123').group())
#a
print(re.search('a(\d*?)d','a23d').group())   #a23d
#a23d

#match匹配原则:从头(第一个字母)匹配,第一个没匹配上就fail
a = '123abc456'
print(re.match('1',a).group())
#1
print(re.search('([0-9]*)([a-z]*)([0-9]*)',a).group(0))
#123abc456
print(re.match('([0-9]*)([a-z]*)([0-9]*)',a).group(1))
#123

#sub替换 ,subn得到替换次数
#sub(pattern, repl, string, count=0, flags=0)
cc = "you grt love, my got test"
print(re.sub('g.t',"have",cc))
#you have love, my have test
print(re.subn('g.t',"have","you grt love, my got test"))
#('you have love, my have test', 2)

#split分隔
test = re.compile(r'\d+')
print(test.split('one1two2three3'))
#['one', 'two', 'three', '']
print(test.split('4one1two2three3'))
#['', 'one', 'two', 'three', '']

猜你喜欢

转载自blog.csdn.net/qq_37550440/article/details/84024321