Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

1.8. 正则处理字符串

1.8.1. 正则替换

				 
import re

string = "TMP AAAAAA\r\nMSG BBBB"

print(re.sub(r'(TMP|MSG)\s', "", string))

				
		

1.8.2. match

				 
#!/usr/bin/python
import re

string = "/aaa/bbb/ccc"
match = re.match(r"/aaa/bbb/(.*)", string)
print(match)
print(match.span())
print(match.string)
print(match.group())
print(match.group(1))
print(match.groups())
print(match.groupdict())				
				
		

输出

				 
<re.Match object; span=(0, 12), match='/aaa/bbb/ccc'>
(0, 12)
/aaa/bbb/ccc
/aaa/bbb/ccc
ccc
('ccc',)
{}				
				
		

1.8.3. 正则查找

				
#!/usr/bin/python
import re

regular = "打开|关闭|结束|暂停"
question = "打开电灯,然后关闭"
pattern = re.compile(regular)
result = pattern.findall(question)
print(result)
				
		
				
#!/usr/bin/python
import re

regular = "(打开|播放)圣经第(.+)卷第(.*)章"
question = "打开圣经第三卷第二章"
pattern = re.compile(regular)
result = pattern.findall(question)
print(result)				
				
		

1.8.4. 正则匹配后返回字典

		
#!/usr/bin/python
import re

m = re.match(r"(?P<firstname>\w+) (?P<lastname>\w+)", "Neo Chen")
print(m.group("firstname"), m.group("lastname"))		
		
		

		
>>> match = re.search(r'(foo)?(bar)?', 'foo')
>>> match and match.groups()[1]
None
>>> match = re.search(r'(foo)?(bar)?', 'foobar')
>>> match and match.groups()[1]
'bar'

match = re.search(r'(?P<foo>foo)?(?P<bar>bar)?', 'foo')
match and match.groupdict().get('bar')

match = re.search(r'(?P<foo>foo)?(?P<bar>bar)?', 'foobar')
match and match.groupdict().get('bar')