>>> import re
>>> regex = re.compile(r
'\b\w{6}\b'
)
# 匹配6个字符的单词
>>> regex.search(
'My phone number is 421-2343-121'
)
>>> text = regex.search(
'My phone number is 421-2343-121'
)
>>> text.group()
# 调用 group() 返回结果
'number'
>>> regex = re.compile(r
'0\d{2}-\d{8}|0\d{3}-\d{7}'
)
# 注意分枝条件的使用
>>> text = regex.search(
'My phone number is 021-76483929'
)
>>> text.group()
'021-76483929'
>>> text = regex.search(
'My phone number is 0132-2384753'
)
>>> text.group()
'0132-2384753'
>>> regex = re.compile(r
'(0\d{2})-(\d{8})'
)
# 括号分组的使用
>>> text = regex.search(
'My phone number is 032-23847533'
)
>>> text.group(0)
'032-23847533'
>>> text.group(1)
'032'
>>> text.group(2)
'23847533'
>>> regex = re.compile(r
'(0\d{2}-)?(\d{8})'
)
# ?之前的分组表示是可选的分组,如果需要匹配真正的?,就使用转义字符\?
>>> text = regex.search(
'My phone number is 032-23847533'
)
>>> text.group()
'032-23847533'
>>> text = regex.search(
'My phone number is 23847533'
)
>>> text.group()
'23847533'
>>> regex = re.compile(r
'(Py){3,5}'
)
# Python 默认是贪心,尽可能匹配最长的字符串
>>> text = regex.search(
'PyPyPyPyPy'
)
>>> text.group()
'PyPyPyPyPy'
>>> regex = re.compile(r
'(Py){3,5}?'
)
# ? 声明非贪心,尽可能匹配最短的字符串
>>> text = regex.search(
'PyPyPyPyPy'
)
>>> text.group()
'PyPyPy'