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'))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章