日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python中正则表达式的简单应用_Python正则表达式详细应用

發(fā)布時間:2024/1/8 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中正则表达式的简单应用_Python正则表达式详细应用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

原文地址:http://www.jb51.net/article/65286.htm

1.了解正則表達(dá)式

正則表達(dá)式是對字符串操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個“規(guī)則字符串”,這個“規(guī)則字符串”用來表達(dá)對字符串的一種過濾邏輯。

正則表達(dá)式是用來匹配字符串非常強大的工具,在其他編程語言中同樣有正則表達(dá)式的概念,Python同樣不例外,利用了正則表達(dá)式,我們想要從返回的頁面內(nèi)容提取出我們想要的內(nèi)容就易如反掌了。

正則表達(dá)式的大致匹配過程是:

1.依次拿出表達(dá)式和文本中的字符比較,

2.如果每一個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。

3.如果表達(dá)式中有量詞或邊界,這個過程會稍微有一些不同。

2.正則表達(dá)式的語法規(guī)則

下面是Python中正則表達(dá)式的一些匹配規(guī)則,圖片資料來自CSDN

3.正則表達(dá)式相關(guān)注解

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

正則表達(dá)式通常用于在文本中查找匹配的字符串。Python里數(shù)量詞默認(rèn)是貪婪的(在少數(shù)語言里也可能是默認(rèn)非貪婪),總是嘗試匹配盡可能多的字

符;非貪婪的則相反,總是嘗試匹配盡可能少的字符。例如:正則表達(dá)式”ab*”如果用于查找”abbbc”,將找到”abbb”。而如果使用非貪婪的數(shù)量

詞”ab*?”,將找到”a”。

注:我們一般使用非貪婪模式來提取。

(2)反斜杠問題

與大多數(shù)編程語言相

同,正則表達(dá)式里使用”\”作為轉(zhuǎn)義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符”\”,那么使用編程語言表示的正則表達(dá)式里將需要4個反

斜杠”\\\\”:前兩個和后兩個分別用于在編程語言里轉(zhuǎn)義成反斜杠,轉(zhuǎn)換成兩個反斜杠后再在正則表達(dá)式里轉(zhuǎn)義成一個反斜杠。

Python里的原生字符串很好地解決了這個問題,這個例子中的正則表達(dá)式可以使用r”\\”表示。同樣,匹配一個數(shù)字的”\\d”可以寫成r”\d”。有了原生字符串,媽媽也不用擔(dān)心是不是漏寫了反斜杠,寫出來的表達(dá)式也更直觀勒。

4.Python Re模塊

Python 自帶了re模塊,它提供了對正則表達(dá)式的支持。主要用到的方法列舉如下

1

2

3

4

5

6

7

8

9

10

#返回pattern對象

re.compile(string[,flag])

#以下為匹配所用函數(shù)

re.match(pattern, string[, flags])

re.search(pattern, string[, flags])

re.split(pattern, string[, maxsplit])

re.findall(pattern, string[, flags])

re.finditer(pattern, string[, flags])

re.sub(pattern, repl, string[, count])

re.subn(pattern, repl, string[, count])

在介紹這幾個方法之前,我們先來介紹一下pattern的概念,pattern可以理解為一個匹配模式,那么我們怎么獲得這個匹配模式呢?很簡單,我們需要利用re.compile方法就可以。例如

1

pattern= re.compile(r'hello')

在參數(shù)中我們傳入了原生字符串對象,通過compile方法編譯生成一個pattern對象,然后我們利用這個對象來進行進一步的匹配。

另外大家可能注意到了另一個參數(shù) flags,在這里解釋一下這個參數(shù)的含義:

參數(shù)flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。

可選值有:

? re.I(全拼:IGNORECASE): 忽略大小寫(括號內(nèi)是完整寫法,下同)

? re.M(全拼:MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖)

? re.S(全拼:DOTALL): 點任意匹配模式,改變'.'的行為

? re.L(全拼:LOCALE): 使預(yù)定字符類 \w \W \b \B \s \S 取決于當(dāng)前區(qū)域設(shè)定

? re.U(全拼:UNICODE): 使預(yù)定字符類 \w \W \b \B \s \S \d \D 取決于unicode定義的字符屬性

? re.X(全拼:VERBOSE): 詳細(xì)模式。這個模式下正則表達(dá)式可以是多行,忽略空白字符,并可以加入注釋。

在剛才所說的另外幾個方法例如 re.match 里我們就需要用到這個pattern了,下面我們一一介紹。

注:以下七個方法中的flags同樣是代表匹配模式的意思,如果在pattern生成時已經(jīng)指明了flags,那么在下面的方法中就不需要傳入這個參數(shù)了。

(1)re.match(pattern, string[, flags])

這個方法將會從string(我們要匹配的字符串)的開頭開始,嘗試匹配pattern,一直向后匹配,如果遇到無法匹配的字符,立即返回

None,如果匹配未結(jié)束已經(jīng)到達(dá)string的末尾,也會返回None。兩個結(jié)果均表示匹配失敗,否則匹配pattern成功,同時匹配終止,不再對

string向后匹配。下面我們通過一個例子理解一下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

__author__= 'CQC'

# -*- coding: utf-8 -*-

#導(dǎo)入re模塊

import re

# 將正則表達(dá)式編譯成Pattern對象,注意hello前面的r的意思是“原生字符串”

pattern= re.compile(r'hello')

# 使用re.match匹配文本,獲得匹配結(jié)果,無法匹配時將返回None

result1= re.match(pattern,'hello')

result2= re.match(pattern,'helloo CQC!')

result3= re.match(pattern,'helo CQC!')

result4= re.match(pattern,'hello CQC!')

#如果1匹配成功

if result1:

# 使用Match獲得分組信息

print result1.group()

else:

print '1匹配失敗!'

#如果2匹配成功

if result2:

# 使用Match獲得分組信息

print result2.group()

else:

print '2匹配失敗!'

#如果3匹配成功

if result3:

# 使用Match獲得分組信息

print result3.group()

else:

print '3匹配失敗!'

#如果4匹配成功

if result4:

# 使用Match獲得分組信息

print result4.group()

else:

print '4匹配失敗!'

運行結(jié)果

1

2

3

4

hello

hello

3匹配失敗!

hello

匹配分析

1.第一個匹配,pattern正則表達(dá)式為'hello',我們匹配的目標(biāo)字符串string也為hello,從頭至尾完全匹配,匹配成功。

2.第二個匹配,string為helloo CQC,從string頭開始匹配pattern完全可以匹配,pattern匹配結(jié)束,同時匹配終止,后面的o CQC不再匹配,返回匹配成功的信息。

3.第三個匹配,string為helo CQC,從string頭開始匹配pattern,發(fā)現(xiàn)到 ‘o' 時無法完成匹配,匹配終止,返回None

4.第四個匹配,同第二個匹配原理,即使遇到了空格符也不會受影響。

我們還看到最后打印出了result.group(),這個是什么意思呢?下面我們說一下關(guān)于match對象的的屬性和方法

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

屬性:

1.string: 匹配時使用的文本。

2.re: 匹配時使用的Pattern對象。

3.pos: 文本中正則表達(dá)式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數(shù)相同。

4.endpos: 文本中正則表達(dá)式結(jié)束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數(shù)相同。

5.lastindex: 最后一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。

6.lastgroup: 最后一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。

方法:

1.group([group1, …]):

獲得一個或多個分組截獲的字符串;指定多個參數(shù)時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數(shù)時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最后一次截獲的子串。

2.groups([default]):

以元組形式返回全部分組截獲的字符串。相當(dāng)于調(diào)用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認(rèn)為None。

3.groupdict([default]):

返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內(nèi)。default含義同上。

4.start([group]):

返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認(rèn)值為0。

5.end([group]):

返回指定的組截獲的子串在string中的結(jié)束索引(子串最后一個字符的索引+1)。group默認(rèn)值為0。

6.span([group]):

返回(start(group), end(group))。

7.expand(template):

將匹配到的分組代入template中然后返回。template中可以使用\id或\g、\g引用分組,但不能使用編號0。\id與\g是等價的;但\10將被認(rèn)為是第10個分組,如果你想表達(dá)\1之后是字符'0',只能使用\g0。

下面我們用一個例子來體會一下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

# -*- coding: utf-8 -*-

#一個簡單的match實例

import re

# 匹配如下內(nèi)容:單詞+空格+單詞+任意字符

m= re.match(r'(\w+) (\w+)(?P.*)','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():", m.group()

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'\g \g\g'):", m.expand(r'\2 \1\3')

### output ###

# m.string: hello world!

# m.re:

# 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!

(2)re.search(pattern, string[, flags])

search方法與match方法極其類似,區(qū)別在于match()函數(shù)只檢測re是不是在string的開始位置匹配,search()會掃描整個string查找匹配,match()只有在0位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match()就返回None。同樣,search方法的返回對象同樣match()返回對象的方法和屬性。我們用一個例子感受一下

1

2

3

4

5

6

7

8

9

10

11

12

13

#導(dǎo)入re模塊

import re

# 將正則表達(dá)式編譯成Pattern對象

pattern= re.compile(r'world')

# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None

# 這個例子中使用match()無法成功匹配

match= re.search(pattern,'hello world!')

if match:

# 使用Match獲得分組信息

print match.group()

### 輸出 ###

# world

(3)re.split(pattern, string[, maxsplit])

按照能夠匹配的子串將string分割后返回列表。maxsplit用于指定最大分割次數(shù),不指定將全部分割。我們通過下面的例子感受一下。

1

2

3

4

5

6

7

import re

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

print re.split(pattern,'one1two2three3four4')

### 輸出 ###

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

(4)re.findall(pattern, string[, flags])

1

2

3

4

5

6

7

8

9

搜索string,以列表形式返回全部能匹配的子串。我們通過這個例子來感受一下

import re

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

print re.findall(pattern,'one1two2three3four4')

### 輸出 ###

# ['1', '2', '3', '4']

(5)re.finditer(pattern, string[, flags])

搜索string,返回一個順序訪問每一個匹配結(jié)果(Match對象)的迭代器。我們通過下面的例子來感受一下

1

2

3

4

5

6

7

8

import re

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

for min re.finditer(pattern,'one1two2three3four4'):

print m.group(),

### 輸出 ###

# 1 2 3 4

(6)re.sub(pattern, repl, string[, count])

使用repl替換string中每一個匹配的子串后返回替換后的字符串。

當(dāng)repl是一個字符串時,可以使用\id或\g、\g引用分組,但不能使用編號0。

當(dāng)repl是一個方法時,這個方法應(yīng)當(dāng)只接受一個參數(shù)(Match對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。

count用于指定最多替換次數(shù),不指定時全部替換。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import re

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

s= 'i say, hello world!'

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

def func(m):

return m.group(1).title()+ ' ' + m.group(2).title()

print re.sub(pattern,func, s)

### output ###

# say i, world hello!

# I Say, Hello World!

(7)re.subn(pattern, repl, string[, count])

返回 (sub(repl, string[, count]), 替換次數(shù))。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import re

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

s= 'i say, hello world!'

print re.subn(pattern,r'\2 \1', s)

def func(m):

return m.group(1).title()+ ' ' + m.group(2).title()

print re.subn(pattern,func, s)

### output ###

# ('say i, world hello!', 2)

# ('I Say, Hello World!', 2)

5.Python Re模塊的另一種使用方式

在上面我們介紹了7個工具方法,例如match,search等等,不過調(diào)用方式都是

re.match,re.search的方式,其實還有另外一種調(diào)用方式,可以通過pattern.match,pattern.search調(diào)用,這樣

調(diào)用便不用將pattern作為第一個參數(shù)傳入了,大家想怎樣調(diào)用皆可。

函數(shù)API列表

1

2

3

4

5

6

7

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags])

search(string[, pos[, endpos]]) | re.search(pattern, string[, flags])

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit])

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags])

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags])

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count])

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count])

具體的調(diào)用方法不必詳說了,原理都類似,只是參數(shù)的變化不同。小伙伴們嘗試一下吧~

小伙伴們加油,即使這一節(jié)看得云里霧里的也沒關(guān)系,接下來我們會通過一些實戰(zhàn)例子來幫助大家熟練掌握正則表達(dá)式的。

總結(jié)

以上是生活随笔為你收集整理的python中正则表达式的简单应用_Python正则表达式详细应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。