| 知乎专栏 |
#!/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',)
{}
#!/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)
#!/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')