Python正則表達式

使用正則表達式,會使得字符串的處理很方便。更多見:iii.run


正則表達式基礎(chǔ)

常用語法

Python中經(jīng)常要對字符串進行處理,處理用戶的輸入,對文本的編輯等等。使用正則表達式,會使得字符串的處理很方便。


Python支持的正則表達式元字符和語法

數(shù)量詞的貪婪模式與非貪婪模式

正則表達式通常用于在文本中查找匹配的字符串。

Python里數(shù)量詞默認(rèn)是貪婪的(在少數(shù)語言里也可能是默認(rèn)非貪婪),總是嘗試匹配盡可能多的字符;非貪婪的則相反,總是嘗試匹配盡可能少的字符。

例如:正則表達式"ab"如果用于查找"abbbc",將找到"abbb"。而如果使用非貪婪的數(shù)量詞"ab?",將找到"a"。

re模塊

開始使用re

Python通過re模塊提供對正則表達式的支持。使用re的一般步驟是先將正則表達式的字符串形式編譯為Pattern實例,然后使用Pattern實例處理文本并獲得匹配結(jié)果(一個Match實例),最后使用Match實例獲得信息,進行其他的操作。

# encoding: UTF-8
import re
def test():
    # 將正則表達式編譯成Pattern對象
    pattern1 = re.compile(r'hello') 
    # 使用Pattern匹配文本,獲得匹配結(jié)果,無法匹配時將返回None
    return pattern1.match('hello world!')
    
if test():
    # 使用Match獲得分組信息
    print ("match")
else:
    print ("not match")

re.compile(strPattern[, flag]):
這個方法用于將字符串形式的正則表達式編譯為Pattern對象, 第二個參數(shù)flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。另外,你也可以在regex字符串中指定模式,比如re.compile('pattern', re.I | re.M)re.compile('(?im)pattern')是等價的。
可選值有:

  • re.I(re.IGNORECASE): 忽略大小寫(括號內(nèi)是完整寫法,下同)
  • M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖)
  • S(DOTALL): 點任意匹配模式,改變'.'的行為
  • L(LOCALE): 使預(yù)定字符類 \w \W \b \B \s \S 取決于當(dāng)前區(qū)域設(shè)定
  • U(UNICODE): 使預(yù)定字符類 \w \W \b \B \s \S \d \D 取決于unicode定義的字符屬性
  • X(VERBOSE): 詳細(xì)模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋。以下兩個正則表達式是等價的:
a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")

re提供了眾多模塊方法用于完成正則表達式的功能。這些方法可以使用Pattern實例的相應(yīng)方法替代,唯一的好處是少寫一行re.compile()代碼,但同時也無法復(fù)用編譯后的Pattern對象。

m = re.match(r'hello', 'hello world!')
print m.group()

re模塊還提供了一個方法escape(string),用于將string中的正則表達式元字符如*/+/?等之前加上轉(zhuǎn)義符再返回,在需要大量匹配元字符時有那么一點用。

Match

Match對象是一次匹配的結(jié)果,包含了很多關(guān)于此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。

屬性:

  • string: 匹配時使用的文本。
  • re: 匹配時使用的Pattern對象。
  • pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數(shù)相同。
  • endpos: 文本中正則表達式結(jié)束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數(shù)相同。
  • lastindex: 最后一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。
  • lastgroup: 最后一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。

方法:

  • group([group1, …]):
    獲得一個或多個分組截獲的字符串;指定多個參數(shù)時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數(shù)時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。
  • **groups([default]): **
    以元組形式返回全部分組截獲的字符串。相當(dāng)于調(diào)用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認(rèn)為None。
  • **groupdict([default]): **
    返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內(nèi)。default含義同上。
  • **start([group]): **
    返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認(rèn)值為0。
  • **end([group]): **
    返回指定的組截獲的子串在string中的結(jié)束索引(子串最后一個字符的索引+1)。group默認(rèn)值為0。
  • **span([group]): **
    返回(start(group), end(group))。
  • **expand(template): **
    將匹配到的分組代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。\id與\g<id>是等價的;但\10將被認(rèn)為是第10個分組,如果你想表達\1之后是字符'0',只能使用\g<1>0。
import re
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')
 
print ("m.string:", m.string)
print ("m.re:", m.re)
print ("m.pos:", m.pos)
print ("m.endpos:", m.endpos)
print ("m.lastindex:", m.lastindex)
print ("m.lastgroup:", m.lastgroup)
 
print ("m.group(1,2):", m.group(1, 2))
print ("m.groups():", m.groups())
print ("m.groupdict():", m.groupdict())
print ("m.start(2):", m.start(2))
print ("m.end(2):", m.end(2))
print ("m.span(2):", m.span(2))
print (r"m.expand(r'\2 \1\3'):", m.expand(r'\2 \1\3'))

輸出內(nèi)容如下:

m.string: hello world!
m.re: re.compile('(\\w+) (\\w+)(?P<sign>.*)')
m.pos: 0
m.endpos: 12
m.lastindex: 3
m.lastgroup: sign
m.group(1,2): ('hello', 'world')
m.groups(): ('hello', 'world', '!')
m.groupdict(): {'sign': '!'}
m.start(2): 6
m.end(2): 11
m.span(2): (6, 11)
m.expand(r'\2 \1\3'): world hello!

Pattern

Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。

Pattern不能直接實例化,必須使用re.compile()進行構(gòu)造。

Pattern提供了幾個可讀屬性用于獲取表達式的相關(guān)信息:

  • pattern: 編譯時用的表達式字符串。
  • flags: 編譯時用的匹配模式。數(shù)字形式。
  • groups: 表達式中分組的數(shù)量。
  • groupindex: 以表達式中有別名的組的別名為鍵、以該組對應(yīng)的編號為值的字典,沒有別名的組不包含在內(nèi)。
import re
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
 
print ("p.pattern:", p.pattern)
print ("p.flags:", p.flags)
print ("p.groups:", p.groups)
print ("p.groupindex:", p.groupindex)
 
### output ###
# p.pattern: (\w+) (\w+)(?P<sign>.*)
# p.flags: 16
# p.groups: 3
# p.groupindex: {'sign': 3}

實例方法[ | re模塊方法]:

  • **match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): **
    這個方法將從string的pos下標(biāo)處起嘗試匹配pattern;如果pattern結(jié)束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結(jié)束就已到達endpos,則返回None。
    pos和endpos的默認(rèn)值分別為0和len(string);
    re.match()無法指定這兩個參數(shù),參數(shù)flags用于編譯pattern時指定匹配模式。
    注意:這個方法并不是完全匹配。當(dāng)pattern結(jié)束時若string還有剩余字符,仍然視為成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。

  • **search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): **
    這個方法用于查找字符串中可以匹配成功的子串。從string的pos下標(biāo)處起嘗試匹配pattern,如果pattern結(jié)束時仍可匹配,則返回一個Match對象;
    若無法匹配,則將pos加1后重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。
    pos和endpos的默認(rèn)值分別為0和len(string));re.search()無法指定這兩個參數(shù),參數(shù)flags用于編譯pattern時指定匹配模式。

# encoding: UTF-8 
import re 
 
# 將正則表達式編譯成Pattern對象 
pattern = re.compile(r'world') 
 
# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None 
# 這個例子中使用match()無法成功匹配 
match = pattern.search('hello world!') 
 
if match: 
    # 使用Match獲得分組信息 
    print (match.group() )
 
### 輸出 ### 
# world
  • **split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): **
    按照能夠匹配的子串將string分割后返回列表。maxsplit用于指定最大分割次數(shù),不指定將全部分割。
import re
 
p = re.compile(r'\d+')
print (p.split('one1two2three3four4'))
 
### output ###
# ['one', 'two', 'three', 'four', '']
  • **findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): **
    搜索string,以列表形式返回全部能匹配的子串。
import re
 
p = re.compile(r'\d+')
print (p.findall('one1two2three3four4'))
 
### output ###
# ['1', '2', '3', '4']
  • **finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): **
    搜索string,返回一個順序訪問每一個匹配結(jié)果(Match對象)的迭代器。
import re
 
p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
    print m.group(),
 
### output ###
# 1 2 3 4
  • **sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): **
    re.sub用于替換字符串中的匹配項。下面一個例子將字符串中的空格 ' ' 替換成 '-' :
import re
text = "he is cool, clever, and so on..."
print (re.sub(r'\s+', '-', text) )

re.sub的函數(shù)原型為:re.sub(pattern, repl, string, count)

其中第二個函數(shù)是替換后的字符串;本例中為'-'

第四個參數(shù)指替換個數(shù)。默認(rèn)為0,表示每個匹配項都替換。

re.sub還允許使用函數(shù)對匹配項的替換進行復(fù)雜的處理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);將字符串中的空格' '替換為'[ ]'。

  • **subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): **
    返回 (sub(repl, string[, count]), 替換次數(shù))。
import re
 
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
 
print (p.subn(r'\2 \1', s))
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print (p.subn(func, s))
 
### output ###
# ('say i, world hello!', 2)
# ('I Say, Hello World!', 2)

以上就是Python對于正則表達式的支持。熟練掌握正則表達式是每一個程序員必須具備的技能。筆者也是看的迷迷糊糊,文章來自cnblog,原版博客基于Python2.4完成,年代有點久,我稍微修改了一下代碼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容