python模式匹配与正则表达式

正则表达式使用方法:

1> 用import re导入正则表达式模块

2> 用re.compile()函数创建一个正则表达式对象(记得使用原始字符串)

3> 向Regex对象的search()方法传入想查找的字符串。它返回一个Match对象

4> 调用Match对象的group()方法,返回实际匹配文本的字符串

import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('my number is 425-444-3467')
print('phone number found ' + mo.group())
======================================================
result:
phone number found 425-444-3467

利用括号分组:

import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('my number is 425-444-3467')
print(mo.group())
print(mo.group(1))
print(mo.group(2))
========================================================
result:
425-444-3467
425
444-3467

用管道匹配多个分组:希望匹配多个表达式中的一个时,可以使用管道

import re
heroRegex = re.compile(r'Batman|Tina Fey')
mo = heroRegex.search('Batman and Tina Fey')
print(mo.group())
mo = heroRegex.search('Tina Fey and Batman')
print(mo.group())
=============================================
result:
Batman
Tina Fey
import re
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search('Batcopter lost a wheel')
print(mo.group())
print(mo.group(1))
====================================================
result:
Batcopter
copter

用问号实现可选匹配:?表示出现0次或一次

import re
batRegex = re.compile(r'Bat(wo)?man')
mo = batRegex.search('Batman lost a wheel')
print(mo.group())
mo = batRegex.search('Batwoman lost a wheel')
print(mo.group())
=============================================
result:
Batman
Batwoman

用星号匹配零次或多次:

import re
batRegex = re.compile(r'Bat(wo)*man')
mo = batRegex.search('Batman lost a wheel')
print(mo.group())
mo = batRegex.search('Batwoman lost a wheel')
print(mo.group())
mo = batRegex.search('Batwowowowoman lost a wheel')
print(mo.group())
===================================================
result:
Batman
Batwoman
Batwowowowoman

用加号匹配一次或多次:

import re
batRegex = re.compile(r'Bat(wo)+man')
mo = batRegex.search('Batman lost a wheel')
print(mo)
mo = batRegex.search('Batwoman lost a wheel')
print(mo.group())
mo = batRegex.search('Batwowowowoman lost a wheel')
print(mo.group())
==================================================
result:
None
Batwoman
Batwowowowoman

用花括号匹配特定次数:

import re
haRegex = re.compile(r'(Ha){2,3}')
mo = haRegex.search('Ha')
print(mo)
mo = haRegex.search('HaHa')
print(mo.group())
mo = haRegex.search('HaHaHa')
print(mo.group())
mo = haRegex.search('HaHaHaHa')
print(mo.group())
===============================
result:
None
HaHa
HaHaHa
HaHaHa

贪心和非贪心匹配:python默认是贪心匹配,eg:(Ha){3,5}默认以匹配更多的实例为准,可在{3,5}后加?表示使用非贪心匹配

import re
haRegex = re.compile(r'(Ha){2,3}?')
mo = haRegex.search('Ha')
print(mo)
mo = haRegex.search('HaHa')
print(mo.group())
mo = haRegex.search('HaHaHa')
print(mo.group())
mo = haRegex.search('HaHaHaHa')
print(mo.group())
==================================
result:
None
HaHa
HaHa
HaHa

findall方法:

import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('person01: 425-444-3467, person02: 425-678-4678')
print(mo.group())
mo = phoneNumRegex.findall('person01: 425-444-3467, person02: 425-678-4678')
print(mo)
============================================================================
result:
425-444-3467
[('425', '444-3467'), ('425', '678-4678')]

字符分类:

import re
# 至少一个数字+空格+一个字母
phoneNumRegex = re.compile(r'\d+\s\w+')
mo = phoneNumRegex.findall('8 c, 7 rrr, qqg, 19 tt')
print(mo)
====================================================
result:
['8 c', '7 rrr', '19 tt']

建立自己的字符分类:在缩写的\d \s \w太宽泛的情况下可以自定义字符集

import re
phoneNumRegex = re.compile(r'[aeiou]')
mo = phoneNumRegex.findall('Hello world')
print(mo)
=========================================
result:
['e', 'o', 'o']

插入字符和美元字符:

1> 插入字符^表示以字符串开头的匹配

2> 美元字符$表示以字符串结束的匹配

3> 同时使用^$字符表示整个子串必须匹配模式,如r'^\d+$'表示全是数字

import re
beginRegex = re.compile(r'^Hello')
mo = beginRegex.findall('Hello world')
print(mo)
endRegex = re.compile(r'\d$')
mo = endRegex.findall('Hello world')
print(mo)
mo = endRegex.findall('Hello world4')
print(mo)
beginEndRegex = re.compile(r'^\d+$')
mo = beginEndRegex.findall('45y889')
print(mo)
mo = beginEndRegex.findall('45889')
print(mo)
====================================
result:
['Hello']
[]
['4']
[]
['45889']

通配字符:.表示匹配除了换行以外的任意字符

import re
beginRegex = re.compile(r'.at')
mo = beginRegex.findall('The cat in the hat sat on the first mat')
print(mo)
==================================================================
result:
['cat', 'hat', 'sat', 'mat']

用.*匹配所有字符:

import re
beginRegex = re.compile(r'First Name:(.*) Last Name:(.*)')
mo = beginRegex.search('First Name:Broad Last Name:Cast')
print(mo.group(1))
print(mo.group(2))
==========================================================
result:
Broad
Cast

正则的第二个参数:

1> DOTALL:全部字符,包括换行

2> IGNORECASE:忽略大小写

3> VERBOSE:忽略空白符和注释

import re
beginRegex = re.compile(r'(.*)last', re.DOTALL | re.IGNORECASE | re.VERBOSE)
mo = beginRegex.search('First Name:Broad Last Name:Cast'
                       'sdf  sdf fs dffsdf dfdfasdf ')
print(mo.group())
===========================================================================
result:
First Name:Broad Last

正则表达式做替换:sub()函数有两个参数,第一个参数用于取代发现的匹配字符串,第二个参数是匹配的内容

import re
agentRegex = re.compile(r'Agent \w+')
mo = agentRegex.sub('Agent xx', 'Agent Alice gave the secret documents to Agent Bob')
print(mo)
====================================================================================
result:
Agent xx gave the secret documents to Agent xx

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperYang_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值