Python中的正则表达式

正则表达式使用步骤

1. 用import re导入正则表达式

2. 用re.compile()函数创建一个Regex对象

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 415-332-9870')

print('Phone number found: '+ mo.group())

创建分组

添加括号将在正则表达式中创建“分组”:(\d\d\d)-(\d\d\d-\d\d\d\d)

然后可以使用group()匹配对象方法,从一个分组获取匹配的文本。向group方法传入0或不传入参数,将返回整个文本,向group方法传入整数1或2,就可以取得匹配文本的不同部分。

group1 = mo.group(1)

group2 = mo.group(2)

print(group1)

print(group2)

一次获得所有的分组,使用groups()方法:

areaCode, mainNumber = mo.groups()

print(areaCode)

print(mainNumber)

不同特殊字符的用法:

“|”希望匹配许多表达式中的一个时,

正则表达式r'Batman|Tina Fey'将匹配Batman或者Tina Fey, 如果它们都出现在被查找的字符串中,第一次出现的匹配文本将作为Match对象返回。

heroRegex = re.compile(r'Batman|Tina Fey')

mo1 = heroRegex.search("Batman and Tina Fey")

print(mo1.group())  # 返回Batman

mo2 = heroRegex.search("Tina Fey and Batman")

print(mo2.group())  # 返回Tina Fey

"|"中的括号分组使用

batRegex = re.compile(r'Bat(man|mobile|copter|bat)')

mo = batRegex.search("Batmobile lost a wheel.")

print(mo.group(1))  # 匹配括号中出现的第一个字符

print(mo.group()) # 匹配整个对应字符

"?"实现可选匹配,匹配这个问号之前的分组零次或一次

batRegex = re.compile(r'Bat(wo)?man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwoman.")

print(mo1.group())  # 返回Batman

print(mo2.group())  # 返回Batwoman

"*"实现匹配零次或多次

batRegex = re.compile(r'Bat(wo)*man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwowowowoman.")

mo3 = batRegex.search("The adventures of Batwoman.")

print(mo1.group())

print(mo2.group())

print(mo3.group())

“+”匹配一次或多次

batRegex = re.compile(r'Bat(wo)+man')

mo1 = batRegex.search("The adventures of Batman.")

mo2 = batRegex.search("The adventures of Batwowowowoman.")

mo3 = batRegex.search("The adventures of Batwoman.")

print(mo1 == None)  # 返回True 没有匹配结果

print(mo2.group())

print(mo3.group())

“{n}”匹配出现的次数

haRegex = re.compile(r'(Ha){3}')

mo1 = haRegex.search('HaHaHa')

print(mo1.group())

mo2 = haRegex.search('Ha')

print(mo2 == None)

贪心和非贪心匹配

在次数后面加上?表示非贪心匹配,如{3,5}?则只匹配3次。

greedyHaRegex = re.compile(r'(Ha){3,5}')

nongreedyHaRegex = re.compile(r'(Ha){3,5}?')

mo1 = greedyHaRegex.search('HaHaHaHaHa')

print(mo1.group())

mo2 = nongreedyHaRegex.search('HaHaHaHaHa')

print(mo2.group())

findall()方法

1. 如果调用在一个没有分组的正则表达式上,findall()将返回一个匹配字符串的列表

2. 如果调用在一个有分组的正则表达式上,findall()将返回一个字符串的元组列表

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

number_str = "Cell:415-555-9999 Work:212-555-0000"

mo = phoneNumRegex.findall(number_str)

print(mo)

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')

number_str = "Cell:415-555-9999 Work:212-555-0000"

mo1 = phoneNumRegex.findall(number_str)

print(mo1)

开始和结束匹配

# ^ and $

beginsWithHello = re.compile(r'^Hello')

mo = beginsWithHello.search("Hello World")

print(mo.group())

endWithNumber = re.compile(r'\d$')

mo1 = endWithNumber.search("Your age is 23")

print(mo1.group())

.*匹配所有字符

nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')

mo2 = nameRegex.search("First Name: Al Last Name: Sweigart")

print(mo2.group())

re.I传入compile第二个参数,忽略大小写

robocop = re.compile(r'robocop',re.I)

mo3 = robocop.search('RoBocop is part man, part machine, all cop')

mo4 = robocop.search('ROBOCOP is part man, part machine')

print(mo3.group())

print(mo4.group())

sub()方法

namesRegex = re.compile(r'Agent \w+')

mo5 = namesRegex.sub('CENSORED','Agent Alice gave the secret to Agent Bob.')

print(mo5)

agentNamesRegex = re.compile(r'Agent (\w)(\w*)')

mo6 = agentNamesRegex.sub(r'*\2','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')

print(mo6)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容