python正則表達式

                       python正則表達式58950e6addf90136876c4a4390be37f0.pngpython



1、re模塊git

   python中處理正則表達式的一個模塊,經過re模塊的方法,把正則表達式pattern編譯成正則正則表達式

對象,以便使用正則對象的方法緩存


1.compile加速ide

re.compile(pattern[, flags])函數


說明:將正則規則編譯成一個Pattern對象,以供接下來使用;第一個參數是規則式,第二個參數是規則選項;返回一個Pattern對象spa

1)參數flag是匹配模式,取值可使用按位或運算符「|」表示同時生效,好比:re.I | re.Mcode

2)flag的可選值:orm

re.I (re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)對象

M (MULTILINE):      多行模式,改變'^'和'$'的行爲

S (DOTALL):        點任意匹配模式,改變'.'的行爲

L (LOCALE):        使預約字符類 \w \W \b \B \s \S 取決於當前區域設定

U (UNICODE):        使預約字符類 \w \W \b \B \s \S \d \D 取決於unicode定義的字符屬性

X (VERBOSE):        詳細模式,正則表達式能夠多行,忽略空白字符,能夠加入註釋


例子:

a和b等價

a = re.compile(r"""\d +  # the integral part

         \.    # the decimal point

         \d *  # some fractional digits""", re.X)

b = re.compile(r"\d+\.\d*")




2.正則原生符r

   表示這個字符串中間的特殊字符不用轉義,好比要表示‘\n’,能夠這樣:r'\n',或者不用原生字符,而是用字符串:‘\\n

例子:

a = r"\n"

b =  "\n"

c = "\\n"

print a

print b

print c


結果:

\n

\n



3.re模塊compile後,patten對象經常使用方法

3.1.match()方法----匹配開始

格式:match(string[, pos[, endpos]])

參數:

1)string:    匹配使用的字符串

2)pos:       開始搜索的索引(即開始搜索string的下標)默認從開頭匹配,如沒有返回None

3)endpos:    結束搜索的索引


例子

import re

pattern = re.compile(r"\w*(hello.*)(world.*)")

result = pattern.match("aahello world huang")

print(result.groups())

結果:

('hello ', 'world huang')




3.2.search()方法----匹配任意位置

   從string的pos下標處起嘗試匹配pattern,若是pattern結束時仍可匹配,則返回一個Match對象;若沒法匹配,則將pos加1後從新嘗試匹配;直到pos=endpos時仍沒法匹配則返回None

格式: search(string[, pos[, endpos]])


例子:

import re

pattern = re.compile(r"\w*(hello.*)(world.*)")

result = pattern.search("aahello world huang")

print(result.groups())

結果:

('hello ', 'world huang')



3.3.findall()方法----匹配全部對象

返回匹配到的所有子串,列表形式

格式:

findall(string[, pos[, endpos]]) 


例子:

import re

pattern = re.compile(r"\d+")

result = pattern.findall("one1two2three3four")

print result

結果:

['1', '2', '3']




3.4.finditer()方法

順序返回匹配結果(Match對象)的迭代器

格式:finditer(string[, pos[, endpos]])


例子:

import re

pattern = re.compile(r"\d+")

result = pattern.finditer("one1two2three3four")

print type(result)

for m in result:

   print type(m)

   print (m.group())


結果:

<type 'callable-iterator'>

<type '_sre.SRE_Match'>

1

<type '_sre.SRE_Match'>

2

<type '_sre.SRE_Match'>

3




# 3.5.split()方法

以匹配到的子串做爲分隔符,返回列表

格式:split(string[, maxsplit])

參數:

maxsplit:用於指定最大分割次數,不指定將所有分割


例子:

import re

pattern = re.compile(r"\d+")

result = pattern.split("one1two2three3four")

print result

結果:

['one', 'two', 'three', 'four']




# 3.6.sub()方法

替換匹配結果的字符串

格式:sub(repl, string[, count]) 

參數:

1)使用repl替換string中每個匹配的子串後返回替換後的字符串:

當repl是一個字符串時,可使用\id或\g<id>、\g<name>引用分組,但不能使用編號0;

當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)


2)count用於指定最多替換次數,不指定時所有替換


例子:

import re

p = re.compile(r'(\w+) (\w+)')

s = 'i say, hello world!'

print(p.sub(r'\2 \1', s))



結果:

say i, world hello!




4.re模塊方法

說明:用法同compile後,patten經常使用方法同樣

4.1.match()和serch()函數

格式:

match( rule , targetString [,flag] )   # 從開始位置開始匹配,若是開頭沒有,則返回無

search( rule , targetString [,flag] )  # 搜索整個字符串


參數:

第一個是正則規則;第二個是目標字符串;第三個是選項(同compile函數的選項)

返回:

若成功,則返回一個Match對象;若失敗,則無返回



4.2.findall()和finditer()函數

格式:

findall( rule , targetString [,flag] )  # 返回全部匹配的字符串,並存爲一個列表

finditer( rule , target [,flag] )             # 返回一個匹配的字符串迭代器



4.3.split()函數

切片,返回一個被切完的子字符串的列表

格式:

split( rule , target [,maxsplit] )



4.4.sub()函數

替換字符串

格式:

sub ( rule , replace , target [,count] )   # 返回一個被替換的字符串

subn(rule , replace , target [,count] )   # 返回一個元組,第一個元素是被替換的字符串,第二個次數




5.match對象和group

每一個組都有一個序號,按定義時從左到右的順序從1開始編號,0表示整個正則表達式自己

group([index|id])   # 獲取匹配的組號,缺省返回組0,表示所有值

groups()         # 返回所有的組

groupdict()       # 返回以組名爲key,匹配的內容爲values的字典


1)經過數字分組

2)經過別名分組


例子:

import re

prog = re.compile(r'(?P<tagname>abc)(.*)(?P=tagname)')

result = prog.match('abc1234567890abc')


print "## groups() ############"

print(result.groups())

print ""


print "## group('tagname') ############"

print result.group('tagname')

print ""


print "## group(1) ############"

print(result.group(1))

print ""


print "## group(2) ############"

print(result.group(2))

print ""


print "## groupdict() ############"

print(result.groupdict())


結果:

## groups() ############

('abc', '1234567890')


## group('tagname') ############

abc


## group(1) ############

abc


## group(2) ############

1234567890


## groupdict() ############

{'tagname': 'abc'}




2、正則表達式分組

  分組就是用一對圓括號「()」括起來的正則表達式,匹配出的內容就表示一個分組。從正則表達式的左邊開始看,看到的第一個左括號「(」表示第一個分組,第二個表示第二個分組,依次類推,須要注意的是,有一個隱含的全局分組(就是0),就是整個正則表達式。

分完組之後,要想得到某個分組的內容,直接使用group(num)和groups()函數去直接提取就行


1.命名分組

  命名分組就是給具備默認分組編號的組另外再給一個別名。命名分組的語法格式以下:

  (?P<name>正則表達式)   #name是一個合法的標識符

 68d2fe6f303576d35c998f72ce882d09.png


2.後向引用

   當用」()」定義了一個正則表達式組後,正則引擎則會把被匹配的組按照順序編號,存入緩存。這樣咱們想在後面對已經匹配過的內容進行引用時,就能夠用」\數字」的方式或者是經過命名分組進行」(?P=name)「進行引用。\1表示引用第一個分組,\2引用第二個分組,以此類推,\n引用第n個組。而\0則引用整個被匹配的正則表達式自己

  ae0a7e0dedd67475628e040f05d4d8ce.png

相關文章
相關標籤/搜索