正则表达式基础补充学习

import re

str = 'Hi \n _12'
print(str)

一、除换行符之外的任意字符

print(re.findall(".",str))
# 连着两个
print(re.findall("..",str))
# 连着三个
print(re.findall("...",str))
print(re.findall("....",str))

二、 字母、数字、下划线

print(re.findall("\w", str))
# 连着两个
print(re.findall("\w\w", str))
# 连着三个
print(re.findall("\w\w\w", str))

三、数字

print(re.findall("\d", str))

四、空格、换行符

print(re.findall("\s", str))

五、非字母、数字、下划线

print(re.findall("\W", str))

六、非数字

print(re.findall("\D", str))

七、非空格、换行符

print(re.findall("\S", str))

例:

str2 = 'Hello World 123'

print(re.findall('e', str2))
print(re.findall('ll', str2))
print(re.findall('l\n', str2))
print(re.findall('[abcd]', str2))
print(re.findall('[12][12]', str2))
print(re.findall('[12]..', str2))
print(re.findall('[a-f]', str2))
print(re.findall('[0-2a-e]', str2))
print(re.findall('[^a-e]', str2))
str3 = '122333 abbccc'

print(re.findall("\d{3}", str3))
print(re.findall("\w{3}", str3))
print(re.findall("1*", str3))
print(re.findall("1*2", str3))
print(re.findall("1*3", str3))
print(re.findall("1+", str3))
print(re.findall("1+2", str3))
print(re.findall("1+3", str3))
print(re.findall("\d*", str3))
print(re.findall("\d+", str3))
print(re.findall("\d+3", str3))
import re 
str = 'X1Y22Y333Y4444'

# 贪婪匹配
print(re.findall("X.*Y",str))
# ['X1Y22Y33Y']

# 惰性匹配
print(re.findall("X.*?Y",str))
# ['X1Y']

print(re.findall("\d*Y",str))
# ['1Y22Y333Y']
print(re.findall("\d.*?Y",str))
# ['1Y','22Y','333Y']
str2 = 'Hello World 123'

exp = re.compile('\w+')
print(exp.findall(str2))
str3 = 'My name is Martini!'
exp = re.compile('is (.*)!')
print(exp.findall(str3))


str4 = 'My name is Martini!My name is Sam!My name is Tom!'
# exp = re.compile('is (.*)!')
# exp = re.compile('is (.*?)!')
print(exp.findall(str4))


str5 = '''
My name is Martini,and i am 25 years old!
My name is Sam,and i am 27 years old!
My name is Tom,and i am 23 years old!'
exp = re.compile('is (.*?),.*?am (\d+)')
# print(exp.findall(str5))
for i,j in exp.findall(str5):
    print(i,j)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值