Python学习笔记(四)——模式匹配与正则表达式

本文详细介绍了Python中正则表达式的使用,包括创建正则对象、匹配模式、分组、可选分配、贪婪与非贪婪匹配、findall方法、自定义字符分类、通配字符、不区分大小写匹配、sub方法替换字符串,以及如何处理复杂的正则表达式。通过一个小项目,演示了如何提取电话号码和电子邮件地址。
摘要由CSDN通过智能技术生成

正则

创建正则表达对象

>>> 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()

正则表达式的复习

  1. import re 将正则模块导入
  2. re.complie() 函数创建一个Regex对象(记得是使用原始字符串)
  3. 向Regex对象的serach() 方法传入想查找的字符串
  4. 调用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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值