正则表达式
匹配分组
字符 | 功能 |
---|---|
| | 或 |
() | 分组 |
\num | 引用分组num匹配到的字符串 |
(?P<name>) | 分组起别名 |
(?P=name) | 引用别名为name分组匹配到的字符串 |
示例
import re
label = '<html><h1>www.itcast.cn</h1></html>'
res = re.match(r'<\w*><\w*>.*</\2></\1>', label)
print(res.group())
<html><h1>www.itcast.cn</h1></html>
import re
label = '<html><h1>www.itcast.cn</h1></html>'
res = re.match(r'<(?P<name1>\w*)><(?P<name2>\w*)>.*</(?P=name2)></(?P=name1)>', label)
print(res.group())
<html><h1>www.itcast.cn</h1></html>
贪婪模式
贪婪模式:在*
、?
、+
、{n,m}
后加上?
>>> import re
>>> re.match(r"aa(\d+?)","aa2343ddd").group(1)
'2'
r
的作用
r
:是原生字符串的意思,不担心反斜杠漏写问题。