Python 正则表达式

import re

customRegex1 = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')  #
r1 = customRegex1.search('455-456-9889')
print(r1.group())
customRegex2 = re.compile(r'\d{3}-\d{3}-\d{4}')  # 用花括号表示重复次数
r2 = customRegex2.search('455-456-9889')
print(r2.group())

customRegex3 = re.compile(r'\d+\s\w+')  # 用\w表示单词\d表示数字\s表示字符串
r3 = customRegex3.findall('12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, 7\
swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partridge')
print(r3)
customRegex4 = re.compile(r'[aeiouAEIOU]')  # 自定义匹配规则用方括号[]
r4 = customRegex4.findall('12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, 7\
swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partridge')
print(r4)

customRegex5 = re.compile(r'^hello')  # 在字符串的开头匹配用^
r5 = customRegex5.findall('hello world')
print(r5)

customRegex6 = re.compile(r'first name (.*) last name (.*)')  # 加上小括号 分组,不加小括号,匹配全部单引号内的部分
r6 = customRegex6.search('first name lucy last name lily')
print(r6.groups(), r6.group(1), r6.group(2))

customRegex7 = re.compile(r'k.*aaa')
r7 = customRegex7.findall('fjlsfdkabdkjofaaabbaaabcdefg')  # 贪心匹配
print(r7)
customRegex8 = re.compile(r'k.*?aaa')
r8 = customRegex8.findall('fjlsfdkabdkjofaaabbaaabcdefg')  # 非贪心匹配  .*?
print(r8)

customRegex9 = re.compile(r'.*')
r9 = customRegex9.findall('fjlsfdkabd\nkjofaaabbaaab\ncdefg')  #
print('r9', r9)
customRegex10 = re.compile(r'.*', re.DOTALL)  # 匹配所有字符和换行符
r10 = customRegex10.search('fjlsfdkabd\nkjofaaabbaaab\ncdefg')
print('r10', r10.group())

customRegex11 = re.compile(r'[aeiou.*]')  # 自定义匹配规则,方括号中的字符不会被转义
r11 = customRegex11.findall('aeioufjlsfdka ... bdkjo***faaabbaaabcdefg')
print('r11', r11)
customRegex12 = re.compile(r'[^aeiou.*]')  # 自定义匹配规则,方括号中的^不代表以后续字符开头,而是代表非后续字符
r12 = customRegex12.findall('aeioufjlsfdka ... bdkjo***faaabbaaabcdefg')
print('r12', r12)
customRegex13 = re.compile(r'aeiou', re.IGNORECASE)  # 忽略大小写  需要传入re.IGNORECASE或re.I
r13 = customRegex13.findall('AeIOUfjlsfdka ... bdkjo***faaabbaaabcdefg')
print('r13', r13)


nameRegex = re.compile(r'Agent \w+')
print(nameRegex.sub('CENSORED',
                    'Agent Alice gave the secret documents to Agent Bob.'))  # 结果CENSORED gave the secret documents to CENSORED.
AgentRegex = re.compile(r'Agent (\w)\w*')
print(AgentRegex.sub(r'\1***',
                     'Agent Alice gave the secret documents to Agent Bob.'))  # sub第一个参数前加r,表示原生字符串,否则\1表示转义,结果第一个字符为乱码

# 复杂的正则表达式
phoneRegex=re.compile(r'''(
(\d{3})
(\s|-|\.)
(\d{3})
(\s|-|\.)
(\d{4})
)''',re.VERBOSE)

print(phoneRegex.findall("abc's number is 222-345-5678"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值