python 正则表达式与字符串匹配

import re
#用正则表达式查找文本模式,
regex0 = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')#返回一个Regax对象
mo0 = regex0.search('my number is 415-555-4242')
print(mo0.group())
#利用括号分组
regex1 = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
mo1 = regex1.search('my number is 415-555-4242')
print(mo1.groups())
#用管道匹配多个分组
heroRegax = re.compile(r'superman|batman')
mo1 = heroRegax.search('superman and batman')
print(mo1.group())
heroRegax = re.compile(r'(super|bat|spyder|aqua|swords|wonder)man')
print(heroRegax.findall('superman and batman,swordsman and spyderman'))
#问号实现可选匹配
heroRegax = re.compile(r'super(wo)?man')
mo1 = heroRegax.search('superwoman and batman')
print(mo1.group())
#用星号实现零次或者多次匹配
heroRegax = re.compile(r'super(wo)*man')
mo1 = heroRegax.search('superwowowoman and batman')
print(mo1.group())
#用花括号匹配特定次数
haRegax = re.compile(r'(ha){3}')
mo = haRegax.search('hahahahaha,i love hangzhou')
print(mo.group())
haRegax = re.compile(r'(ha){3,}')
mo = haRegax.search('hahahahaha,i love hangzhou')
print(mo.group())
haRegax = re.compile(r'(ha){3,5}')
print((haRegax.search('hahahahaha,i love hangzhou')).group())
haRegax = re.compile(r'(ha){3,5}?')#非贪心
print((haRegax.search('hahahahaha,i love hangzhou')).group())
###插入符号^和美元符号$,
atRegex = re.compile(r'^hello')
print(atRegex.search('hello,dad!'))
atRegex = re.compile(r'hello$')
print(atRegex.search('dad!hello'))
#通配字符.
atRegex = re.compile(r'.man')
print(atRegex.findall('superman and batman,swordsman and aquaman'))
#点-星字符
atRegex = re.compile(r'family:(.*)name:(.*)')
print(atRegex.findall('family:xiao name:haipeng '))
##\d,\w,\s分别匹配数字、单词和空格,\D,\W,\S取反
phoneNumRegex = re.compile(r'(\d+\s\w)')
print(phoneNumRegex.findall('12 drummers,11 pipers,10 lords'))

猜你喜欢

转载自blog.csdn.net/fuck_you_sb/article/details/89677652