正则处理字符串
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)