正则
创建正则表达对象
>>> import re
查找段落中的电话号码 ‘xxx-xxx-xxxx’
\d
表示一个数字字符
re.compile()
传递原始字符串
phoneNumRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
匹配Regex对象
>>> import re
>>> phoneNumRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
>>> mo = phoneNumRegex.search('My number is 123-456-7890')
>>> mo.group()
'123-456-7890'
>>> print(mo)
<re.Match object; span=(13, 25), match='123-456-7890'>
re.compile(r'\d{3}-\d{3}-\d{4}').search('My number is 123-456-7890').group()
正则表达式的复习
- 用
import re
将正则模块导入 - 用
re.complie()
函数创建一个Regex对象(记得是使用原始字符串) - 向Regex对象的
serach()
方法传入想查找的字符串 - 调用Match对象的
group()
,反会实际匹配文本的字符串
用正则表达式匹配更多模式
利用括号分组
>>> phoneNumRegex = re.compile(r'(\d{3})-(\d{3}-\d{4})')
>>> mo = phoneNumRegex.search('My number is 123-456-7890')
>>> mo.group()
'123-456-7890'
>>> mo.group(1)
'123'
>>> mo.group(2)
'456-7890'
>>> mo.group(0)
'123-456-7890'
>>> mo.groups()
('123', '456-7890')
当使用括号的时候\(
和\)
来表示
>>> phoneNumRegex = re.compile(r'(\(\d{3}\)) (\d{3}-\d{4})')
>>> mo = phoneNumRegex.search('My number is (123) 456-7890')
>>> mo
<re.Match object; span=(13, 27), match='(123) 456-7890'>
>>> mo.groups()
('(123)', '456-7890')
利用管道技术分组
>>> heroRegex = re.compile(r'Tom|Job')
>>> mo = heroRegex.search('Tom is better Job')
>>> mo1 = heroRegex.search('Job is better Tom')
>>> mo
<re.Match object; span=(0, 3), match='Tom'>
>>> mo.group()
'Tom'
>>> mo1.group()
'Job'
用 “?” 实现可选分配
(wo)?
表示匹配时出现零次或者一次
>>> batRegex = re.compile(r'Bar(wo)?man')
>>> temp1 = batRegex.search('Barman')
>>> temp2 = batRegex.search('Barwoman')