正则表达式匹配与查找
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了正则表达式匹配与查找相关的知识,希望对你有一定的参考价值。
import re
datepat = re.compile(r‘(\d+)/(\d+)/(\d+)‘)
m = datepat.match(‘11/27/2012‘)
print(m)
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(3))
print(m.groups())
month, day, year = m.groups()
text = ‘Today is 11/27/2012. PyCon starts 3/13/2013.‘
datepat.findall(text)
for month, day, year in datepat.findall(text):
print(‘{}-{}-{}‘.format(year, month, day))
输出:
<_sre.SRE_Match object; span=(0, 10), match=‘11/27/2012‘>
11/27/2012
11
27
2012
(‘11‘, ‘27‘, ‘2012‘)
2012-11-27
2013-3-13
text = ‘@[email protected]$python‘
m = re.search(r"\w+", text)
if m:
print(m.group(0)) #python
else:
print(‘not match‘)
def test_findall_search():
str1 = ‘456abc789abc8910abc‘
re_str = re.compile(r‘\d+‘)
re_findall = re_str.findall(str1)
print(re_findall) #[‘456‘,‘789‘,‘8910‘]
re_search = re_str.search(str1)
print(re_search) #<_sre.SRE_Match object; span=(0, 3), match=‘456‘>
print(re_search.group(0)) #456
test_findall_search()
本文出自 “大荒芜经” 博客,请务必保留此出处http://2892931976.blog.51cto.com/5396534/1755210
以上是关于正则表达式匹配与查找的主要内容,如果未能解决你的问题,请参考以下文章