python正則表達式-re模塊

目錄:html

1、正則函數python

2、re模塊調用正則表達式

3、貪婪模式express

4、分組網絡

5、正則表達式修飾符函數

6、正則表達式模式工具

7、常見的正則表達式學習

 

導讀:編碼

  想要使用python的正則表達式功能就須要調用re模塊,re模塊爲高級字符串處理提供了正則表達式工具。模塊中提供了很多有用的函數,好比:compile函數、match函數、search函數、findall函數、finditer函數、split函數、sub函數、subn函數等。接下來本文將會介紹這些函數的使用狀況,而後經過分析編譯流程對比兩種re模塊的調用方式,以後會介紹其餘一些應用正則表達式須要知道的理論知識,最後經過一些經典的實例將以前學習的理論應用於實際。讓咱們開始正則表達式的學習之旅吧~~~spa

 

1、正則函數

1. re.match函數

功能:re.match嘗試從字符串的起始位置匹配一個模式,若是匹配成功則返回一個匹配的對象,若是不是起始位置匹配成功的話,match()就返回none。

語法:re.match(pattern,string,flags=0)

例子:

1 s = "12abc345ab"
2 m = re.match(r"\d+", s)     ### \d表示匹配數字,至關於[0-9],+表示匹配一個或多個字符
3 print(m.group())    # answer:12     ### match只能匹配一次,group()返回匹配的完整字符串
4 print(m.span())     # answer:(0, 2) ### span()返回包含起始、結束位置的元組
5 
6 m = re.match(r"\d{3,}", s)  ### {3,}規定了匹配最少3個字符,match從起始位置匹配,匹配不到3個字符返回none
7 print(m)    # answer:None

注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

2. re.search函數

功能:re.search 掃描整個字符串並返回第一個成功的匹配,若是匹配成功re.search方法返回一個匹配的對象,不然返回None。

語法:re.search(pattern, string, flags=0)

例子:

1 s = "12abc345ab"
2 m = re.search(r"\d{3,}", s) ### search與match相比的優點,匹配整個字符串,而match只從起始位置匹配
3 print(m.group())    # answer:345
4 print(m.span())     # answer:(5, 8)
5 
6 m = re.search(r"\d+", s)    ### search和match同樣,只匹配一次
7 print(m.group())    # answer:12
8 print(m.span())     # answer:(0, 2)

注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

 3. re.sub函數

功能:re.sub用於替換字符串中的匹配項。

語法:re.sub(pattern, repl, string, count=0, flags=0)

repl參數能夠爲替換的字符串,也能夠爲一個函數。

  • 若是repl是字符串,那麼就會去替換字符串匹配的子串,返回替換後的字符串;
  • 若是repl是函數,定義的函數只能有一個參數(匹配的對象),並返回替換後的字符串。

例子:

1 phone = "2004-959-559 # 這是一個國外電話號碼"
2 ### 刪除字符串中的 Python註釋
3 num = re.sub(r'#.*$', "", phone)    ### '.*'表示匹配除了換行符之外的0個或多個字符,’#...'表示匹配註釋部分,'$'表示匹配到字符末尾
4 print("電話號碼是:", num)        # answer:電話號碼是: 2004-959-559
5 ### 刪除非數字(-)的字符串
6 num = re.sub(r'\D', "", phone)    ### '\D'表示匹配非數字字符,至關於[^0-9]  
7 print("電話號碼是:", num)        # answer:電話號碼是: 2004959559

count可指定替換次數,不指定時所有替換。例如:

1 s = 'abc,123,ef'
2 s1 = re.sub(r'[a-z]+', '*', s)
3 print(s1)    # answer: *,123,*
4 s2 = re.sub(r'[a-z]+', '*', s, count=1)
5 print(s2)    # answer: *,123,ef

repl能夠爲一個函數。例如:

1 # 調用函數對每個字符進行替換,獲得了不一樣的替換結果
2 def more(matched):
3     print(matched.group())
4     return "*" * len(matched.group())
5 s = 'abc,123,ef'
6 s = re.sub(r"[a-z]+", more, s)
7 print(s)
8 # answer1: abc  answer2: ef  answer3: ***,123,**

 注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

4. re.subn函數

功能:和sub函數差很少,可是返回結果不一樣,返回一個元組「(新字符串,替換次數)」

例子:

1 s = 'abc,123,ef'
2 s1 = re.subn(r'[a-z]+', '*', s)
3 print(s1)    # answer: ('*,123,*', 2)
4 s2 = re.subn(r'[a-z]+', '*', s, count=1)
5 print(s2)    # answer: ('*,123,ef', 1)

注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

5. re.compile函數

功能:compile 函數用於編譯正則表達式,生成一個正則表達式( Pattern )對象,供 match() 和 search() 這兩個函數使用。若是匹配成功則返回一個Match對象。

語法:re.compile(pattern[, flags])

注:compilte函數調用狀況比較複雜,下面會有一節專門講解。

6. findall函數

功能:在字符串中找到正則表達式所匹配的全部子串,並返回一個列表,若是沒有找到匹配的,則返回空列表。

語法:findall(string[, pos[, endpos]])

例子:

1 s = "12abc345ab"
2 ms = re.findall(r"\d+", s)  ### findall匹配全部字符,而match和search只能匹配一次
3 print(ms)       # answer:['12', '345']
4 
5 ms = re.findall(r"\d{5}", s)    ### {5}表示匹配5個字符,沒有匹配到,返回空列表
6 print(ms)       # answer:[]

注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

7. re.finditer函數

功能:在字符串中找到正則表達式所匹配的全部子串,並把它們做爲一個迭代器返回。

語法:re.finditer(pattern, string, flags=0)

例子:

1 s = "12abc345ab"
2 for m in re.finditer(r"\d+", s):    ### finditer返回的是迭代器
3     print(m.group())    # answer1:12 ,answer2:345
4     print(m.span())     # answer1:(0, 2) ,answer2:(5, 8)

注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

8. re.split函數

功能:split 方法用pattern作分隔符切分字符串,分割後返回列表。若是用'(pattern)',那麼分隔符也會返回。

語法:re.split(pattern, string[, maxsplit=0, flags=0])

例子:

1 m = re.split('\W+', 'dog,dog,dog.')     ### '\W'表示匹配非字母數字及下劃線,在這裏匹配的就是','和'.',而後按這些字符分割
2 print(m)    # answer:['dog', 'dog', 'dog', '']
3 m = re.split('(\W+)', 'dog,dog,dog.')   ### 使用'(pattern)',連帶分隔符一塊兒返回
4 print(m)    # answer:['dog', ',', 'dog', ',', 'dog', '.', '']
5 m = re.split('\W+', 'dog,dog,dog.', maxsplit=1)  ### 分隔次數,maxsplit=1 分隔一次,默認爲 0,不限制次數。
6 print(m)    # answer:['dog', 'dog,dog.']

 注:例子中涉及部分還未講解的知識,若例子未看懂,能夠將下面內容都看完後再回過頭來看。

小結

1. 函數辨析:match和search的區別

re.match只匹配字符串的開始,若是字符串開始不符合正則表達式,則匹配失敗,函數返回None;

re.search匹配整個字符串,直到找到一個匹配。

2. 函數辨析:3個匹配函數match、search、findall

match 和 search 只匹配一次 ,匹配不到返回None,findall 查找全部匹配結果。

3. 函數返回值

函數re.finditer 、 re.match和re.search 返回匹配對象,而findall、split返回列表。

4. re.compile函數是個謎。

 

2、re模塊調用

re模塊的使用通常有兩種方式:

方法1:

直接使用上面介紹的 re.match, re.search 和 re.findall 等函數對文本進行匹配查找。

方法2:

(1)使用compile 函數將正則表達式的字符串形式編譯爲一個 Pattern 對象;

(2)經過 Pattern 對象提供的一系列方法對文本進行匹配查找,得到匹配結果(一個 Match 對象);

(3)最後使用 Match 對象提供的屬性和方法得到信息,根據須要進行其餘的操做。

 接下來重點介紹一下compile函數。

 

re.compile函數用於編譯正則表達式,生成一個Pattern對象,調用形式以下:

re.compile(pattern[, flag])

其中,pattern是一個字符串形式的正則表達式,flag是一個可選參數(下一節具體講解)。

例子:

1 import re
2 # 將正則表達式編譯成Pattern對象
3 pattern = re.compile(r'\d+')

利用Pattern對象能夠調用前面提到的一系列函數進行文本匹配查找了,可是這些函數的調用與以前有一些小差異。

1. match函數

 使用語法:

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

這個以前講解過了。

(2)Pattern對象:match(string[, pos[, endpos]])

其中,string 是待匹配的字符串,pos 和 endpos 是可選參數,指定字符串的起始和終點位置,默認值分別是 0 和 len (字符串長度)。所以,當不指定 pos 和 endpos 時,match 方法默認匹配字符串的頭部。當匹配成功時,返回一個 Match 對象,若是沒有匹配上,則返回 None。

例子:

 1 pattern = re.compile(r"\d+")
 2 m = pattern.match('one12twothree34four')    ### 這種狀況下和re.match同樣了
 3 print(m)      # answer: None
 4 m = pattern.match('one12twothree34four', 3, 15)
 5 print(m)      # 返回一個Match對象 answer: <_sre.SRE_Match object; span=(3, 5), match='12'>
 6 print(m.group())    # 等價於 print(m.group(0)) answer: 12
 7 print(m.start(0))   # answer: 3
 8 print(m.end(0))     # answer: 5
 9 print(m.span(0))    # answer: (3, 5)
10 ### 對比
11 s = 'one12twothree34four'
12 s = re.match(r"\d+", s)
13 print(s)        # answer: None

當匹配成功時會返回一個Match對象,其中:

  • group([0, 1, 2,...]): 可返回一個或多個分組匹配的字符串,若要返回匹配的所有字符串,可使用group()或group(0)。
  • start(): 匹配的開始位置。
  • end(): 匹配的結束位置。
  • span(): 包含起始、結束位置的元組。等價於(start(), end())。
  • groups(): 返回分組信息。等價於(m.group(1), m.group(2))。
  • groupdict(): 返回命名分組信息。

例子:

 1 pattern = re.compile(r"([a-z]+) ([a-z]+)", re.I)   ### re.I 表示忽略大小寫, ()表示一個分組,因此這裏有2個分組。([a-z]+)表示匹配1個或多個字母
 2 m = pattern.match('hello nice world')
 3 print(m.groups())       # answer: ('hello', 'nice')
 4 print(m.group(0))       # 等價於 m.group() answer: 'hello nice'。返回匹配的所有字符串。
 5 print(m.span(0))        # answer: (0, 10)。返回匹配的所有字符串的起始位置。等價於(m.start(0), m.end(0))
 6 print(m.start(0))       # answer: 0
 7 print(m.end(0))         # answer: 10
 8 print(m.group(1))       # answer: hello。返回第一個分組匹配字符串。
 9 print(m.span(1))        # answer: (0, 5)。返回第一個分組匹配字符串的起始位置。
10 print(m.start(1))       # answer: 0
11 print(m.end(1))         # answer: 5
12 print(m.group(2))       # answer: nice。返回第二個分組匹配字符串。
13 print(m.span(2))        # answer: (6, 10)。返回第二個分組匹配字符串的起始位置。
14 print(m.start(2))       # answer: 6
15 print(m.end(2))         # answer: 10

2. search函數

使用語法:

(1)re.search(pattern, string, flags=0)

這個函數前面已經講解過了。

(2)Pattern對象:search(string[, pos[, endpos]])

例子:

 1 pattern = re.compile('\d+')
 2 m = pattern.search('one12twothree34four')
 3 print(m.group())        # answer: 12
 4 print(m.span())         # answer: (3, 5)
 5 # print(m.group(1))     # answer: 報錯,不存在
 6 print(m.groups())       # 等價於(m.group(1),...) answer: ()
 7 m = pattern.search('one12twothree34four', 10, 30)
 8 print(m.groups())       # answer: ()
 9 print(m.group())        # answer: 34
10 print(m.span())         # answer: (13, 15)

3. findall函數

使用語法:

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

這個函數前面已經講解過了。

(2)Pattern對象:findall(string[, pos[, endpos]])

findall 以列表形式返回所有能匹配的子串,若是沒有匹配,則返回一個空列表。

例子:

1 pattern = re.compile(r'\d+')
2 s1 = pattern.findall('hello world 123 456 789')
3 s2 = pattern.findall('one12twothree34four56', 0, 15)
4 print(s1)       # answer: ['123', '456', '789']
5 print(s2)       # answer: ['12', '34']

4. finditer函數

使用語法:

(1)re.finditer(pattern, string, flags=0)

這個函數前面已經講解過了。

(2)Pattern對象:finditer(string[, pos[, endpos]])

finditer 函數與 findall 相似,可是它返回每個匹配結果(Match 對象)的迭代器。

 例子:

1 pattern = re.compile(r'\d+')
2 s1 = pattern.finditer('hello world 123 456 789')
3 s2 = pattern.finditer('one12twothree34four56', 0, 15)
4 for m in s1:
5     print(m.group())    # answer1: 123, answer2: 456, answer3: 789
6     print(m.span())     # answer1:(12, 15), answer2:(16, 19), answer3:(20, 23)
7 for m in s2:
8     print(m.group())    # answer1: 12, answer2: 34
9     print(m.span())     # answer1:(3, 5), answer2:(13, 15)

5. split函數

使用語法:

(1)re.split(pattern, string[, maxsplit=0, flags=0])

這個函數前面已經講解過了。

(2)Pattern對象:split(string[, maxsplit]])

maxsplit 可指定分割次數,不指定將對字符串所有分割。

例子:

1 s = "a,1;b 2, c"
2 m = re.compile(r'[\s\,\;]+')
3 print(m.split(s))       # answer: ['a', '1', 'b', '2', 'c']
4 m = re.compile(r'[\s\,\;]+')
5 print(m.split(s, maxsplit=1))  # answer: ['a', '1;b 2, c']

 6. sub函數

 使用語法:

(1)re.sub(pattern, repl, string, count=0, flags=0)

這個函數前面已經講解過了。

(2)Pattern對象:sub(repl, string[, count])

當repl爲字符串時,能夠用\id的形式引用分組,但不能使用編號0;當repl爲函數時,返回的字符串中不能再引用分組。

1 pattern = re.compile(r'(\w+) (\w+)')
2 s = "ni 123, hao 456"
3 def func(m):
4     return 'hi'+' '+m.group(2)
5 print(pattern.sub(r'hello world', s))   # answer: "hello world, hello world"
6 print(pattern.sub(r'\2 \1', s))         # answer: "123 ni, 456 hao"
7 print(pattern.sub(func, s))             # answer: "hi 123, hi 456"
8 print(pattern.sub(func, s, 1))          # answer: "hi 123, hao 456"

7. subn函數

subn和sub相似,也用於替換操做。使用語法以下:
Pattern對象:subn(repl, string[, count])

返回一個元組,元組第一個元素和sub函數的結果相同,元組第二個元素返回替換次數。

例子:

1 p = re.compile(r'(\w+) (\w+)')
2 s = 'hello 123, hello 456'
3 def func(m):
4     return 'hi' + ' ' + m.group(2)
5 print(p.subn(r'hello world', s))    # answer: ('hello world, hello world', 2)
6 print(p.subn(r'\2 \1', s))          # answer: ('123 hello, 456 hello', 2)
7 print(p.subn(func, s))              # answer: ('hi 123, hi 456', 2)
8 print(p.subn(func, s, 1))           # answer: ('hi 123, hello 456', 1)

小結:

1. 使用Pattern對象的match、search、findall、finditer等函數能夠指定匹配字符串的起始位置。

2. 對re模塊的兩種使用方式進行對比:

  • 使用 re.compile 函數生成一個 Pattern 對象,而後使用 Pattern 對象的一系列方法對文本進行匹配查找;
  • 直接使用 re.match, re.search 和 re.findall 等函數直接對文本匹配查找。

 例子:

 1 # 方法1
 2 # 將正則表達式先編譯成 Pattern 對象
 3 pattern = re.compile(r'\d+')
 4 print(pattern.match('123, 123'))
 5 print(pattern.search('234, 234'))
 6 print(pattern.findall('345, 345'))
 7 # 方法2
 8 print(re.match(r'\d+', '123, 123'))
 9 print(re.search(r'\d+', '234, 234'))
10 print(re.findall(r'\d+', '345, 345'))

在上述例子中,咱們發現他們共用了同一個正則表達式,代表上看好像沒發現什麼問題,可是當咱們結合正則表達式的匹配過程進行分析時,就會發現這兩種調用方式的效率是不同的。使用正則表達式進行匹配的流程以下圖所示:

因此匹配流程是先對正則表達式進行編譯,而後獲得一個對象,再使用該對象對須要匹配的文本進行匹配。這時咱們就發現方式2會對正則表達式進行了屢次編譯,這樣效率不就下降了嘛。

因此咱們能夠獲得以下結論

若是一個正則表達式要用屢次,那麼出於效率考慮,咱們能夠預先編譯正則表達式,而後調用的一系列函數時複用。若是直接使用re.match、re.search等函數,則須要每一次都對正則表達式進行編譯,效率就會下降。所以在這種狀況下推薦使用第一種方式。

 

 3、貪戀匹配

 正則表達式匹配時默認的是貪戀匹配,也就是會盡量多的匹配更多字符。若是想使用非貪戀匹配,能夠在正則表達式中加上'?'。

下面,咱們來看1個實例:

1 content = 'a<exp>hello world</exp>b<exp>ni hao</exp>c'
2 pattern = re.compile(r'<exp>.*</exp>')
3 s = pattern.findall(content)    ### 貪婪匹配,會在匹配到第一個</exp>時繼續向右匹配,查找更長的匹配子串
4 print(s)        # answer: ['<exp>hello world</exp>b<exp>ni hao</exp>']
5 pattern2 = re.compile(r'<exp>.*?</exp>')
6 s2 = pattern2.findall(content)
7 print(s2)       # answer: ['<exp>hello world</exp>', '<exp>ni hao</exp>']

 

4、分組

若是你想要提取子串或是想要重複提取多個字符,那麼你能夠選擇用定義分組的形式。用()就能夠表示要提取的分組(group),接下來用幾個實例來理解一下分組的使用方式:

例子1:

1 m = re.match(r'(\d{4})-(\d{3,8})$', '0528-86889099')
2 print(m.group())        # answer: 0528-86889099
3 print(m.group(1))       # answer: 0528
4 print(m.group(2))       # answer: 86889099
5 print(m.groups())       # answer: ('0528', '86889099')

正則表達式'(\d{4})-(\d{3, 8})$'表示匹配兩個分組,第一個分組(\d{4})是一個有4個數字的子串,第二個分組(\d{3,8})表示匹配一個數字子串,子串長度爲3到8之間。

例子2:

1 s = 'ab123.456.78.90c'
2 m = re.search(r'(\d{1,3}\.){3}\d{1,3}', s)
3 print(m.group())    # answer: 123.456.78.90

正則表達式'(\d{1,3}\.){3}\d{1,3}‘的匹配過程分爲兩個部分,'(\d{1,3}\.){3}'表示匹配一個長度爲1到3之間的數字子串加上一個英文句號的字符串,重複匹配 3 次該字符串,'\d{1,3}'表示匹配一個1到3位的數字子串,因此最後獲得結果123.456.78.90。

例子3:

1 line = "Cats are smarter than dogs"
2 matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
3 if matchObj:
4     print(matchObj.group())     # answer: Cats are smarter than dogs
5     print(matchObj.group(1))    # answer: Cats
6     print(matchObj.group(2))    # answer: smarter
7 else:
8     print("No match!!")

(.*)第一個分組,.* 表明匹配除換行符以外的全部字符。(.*?) 第二個匹配分組,.*? 後面加了個問號,表明非貪婪模式,只匹配符合條件的最少字符。後面的一個 .* 沒有括號包圍,因此不是分組,匹配效果和第一個同樣,可是不計入匹配結果中。

group() 等同於group(0),表示匹配到的完整文本字符;

group(1) 獲得第一組匹配結果,也就是(.*)匹配到的;

group(2) 獲得第二組匹配結果,也就是(.*?)匹配到的;

由於只有匹配結果中只有兩組,因此若是填 3 時會報錯。

擴展:其餘組操做如:命名組的使用、定義無捕獲組、使用反向引用等,這部份內容還未弄懂,想了解的同窗能夠查看如下連接http://wiki.jikexueyuan.com/project/the-python-study-notes-second-edition/string.html

 

5、正則表達式修飾符

正則表達式能夠包含一些可選標誌修飾符來控制匹配的模式。修飾符被指定爲一個可選的標誌。多個標誌能夠經過按位 OR(|) 它們來指定。

re.I 忽略大小寫。
re.L 作本地化識別(locale-aware)匹配。對中文支持很差。
re.M 多行匹配,影響 ^ 和 $
re.S 單行。'.' 匹配包括換行在內的全部字符
re.U 根據Unicode字符集解析字符。這個標誌影響 \w, \W, \b, \B.
re.X 忽略多餘空白字符,讓表達式更易閱讀。

 例子:

1 s = "123abCD45ABcd"
2 print(re.findall(r"[a-z]+", s))         # answer: ['ab', 'cd']
3 print(re.findall(r"[a-z]+", s, re.I))   # answer: ['abCD', 'ABcd']

 

6、正則表達式模式

下面列出了正則表達式模式語法中的特殊元素。

^ 匹配字符串的開頭。例如,^\d表示必須以數字開頭。
$ 匹配字符串的末尾。例如,\d$表示必須以數字結束。如果^py$就只能匹配'py'了。
. 匹配任意字符,除了換行符「\n",當re.DOTALL標記被指定時,則能夠匹配包括換行符的任意字符。例如,要匹配包括 '\n' 在內的任何字符,請使用象 '[.\n]' 的模式。
[...] 用來表示一組字符,單獨列出。例如:[amk] 匹配 'a','m'或'k'
[^...] 不在[]中的字符。例如:[^abc] 匹配除了a,b,c以外的字符。
* 匹配0個或多個的表達式。
+ 匹配1個或多個的表達式。
? 匹配0個或1個由前面的正則表達式定義的片斷,非貪婪方式
{n}  精確匹配n個前面表達式。例如, o{2} 不能匹配 "Bob" 中的 "o",可是能匹配 "food" 中的兩個 o。
{n,} 匹配 n 個前面表達式。例如, o{2,} 不能匹配"Bob"中的"o",但能匹配 "foooood"中的全部 o。"o{1,}" 等價於 "o+"。"o{0,}" 則等價於 "o*"。
{n, m} 匹配 n 到 m 次由前面的正則表達式定義的片斷,貪婪方式
a| b 匹配a或b。例如,(P|p)ython能夠匹配'Python'或者'python'。
(re) 匹配括號內的表達式,也表示一個組
(?imx) 正則表達式包含三種可選標誌:i, m, 或 x 。隻影響括號中的區域。
(?-imx) 正則表達式關閉 i, m, 或 x 可選標誌。隻影響括號中的區域。
(?: re) 相似 (...), 可是不表示一個組
(?imx: re) 在括號中使用i, m, 或 x 可選標誌
(?-imx: re) 在括號中不使用i, m, 或 x 可選標誌
(?#...) 註釋.
(?= re) 前向確定界定符。若是所含正則表達式,以 ... 表示,在當前位置成功匹配時成功,不然失敗。但一旦所含表達式已經嘗試,匹配引擎根本沒有提升;模式的剩餘部分還要嘗試界定符的右邊。
(?! re) 前向否認界定符。與確定界定符相反;當所含表達式不能在字符串當前位置匹配時成功
(?> re) 匹配的獨立模式,省去回溯。
\w 匹配包括下劃線的任何單詞字符。等價於'[A-Za-z0-9_]'
\W 匹配任何非單詞字符。等價於 '[^A-Za-z0-9_]'
\s 匹配任意空白字符,等價於 [\t\n\r\f]
\S 匹配任意非空字符
\d 匹配任意數字,等價於 [0-9]
\D 匹配任意非數字,等價於[^0-9]
\A 匹配字符串開始
\Z 匹配字符串結束,若是是存在換行,只匹配到換行前的結束字符串。
\z 匹配字符串結束
\G 匹配最後匹配完成的位置。
\b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, 'er\b' 能夠匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B 匹配非單詞邊界。例如,'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\n, \t, 等. 匹配一個換行符。匹配一個製表符。等
\1...\9 匹配第n個分組的內容。
\10 匹配第n個分組的內容,若是它經匹配。不然指的是八進制字符碼的表達式。

 

7、常見的正則表達式

一般狀況下,經過實例學習是一個高效的途徑。接下來我將整理一些常見的正則表達式應用實例,你們能夠試着將前面學的理論知識應用於實踐啦。

(1)匹配國內1三、1五、18開頭的手機號碼的正則表達式

^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[0-9])\d{8}$

(2)匹配中文的正則表達式

中文的unicode編碼範圍主要在 [\u4e00-\u9fa5],這個範圍之中不包括全角(中文)標點。當咱們想要把文本中的中文漢字提取出來時可使用以下方式:

1 title = u'你好,hello,世界' 2 pattern = re.compile(r'[\u4e00-\u9fa5]+') 3 s = pattern.findall(title) 4 print(s) # answer: ['你好', '世界']

 (3)匹配由數字、26個英文字母或下劃線組成的字符串的正則表達式

^\w+$  #等價於 ^[0-9a-zA-Z_]+$

(4)匹配金額,精確到 2 位小數

^[0-9]+(.[0-9]{2})?$

(5)提取文本中的URL連接

^(f|ht){1}(tp|tps):\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- ./?%&=]*)?

(6)匹配身份證號碼

15位:^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$
18位:^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$

(7)匹配整數

^[1-9]\d*$        # 正整數
^-[1-9]\d*$       # 負整數
^-?[1-9]\d*$      # 整數
^[1-9]\d*|0$      # 非負整數
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$    # 正浮點數

 注:因爲平時正則用的太少,因此沒有太多實用經驗,本文內容只是研讀了多個博客文章以後的整理筆記,對正則的解讀很淺顯。正則的相關知識太多,這裏只是整理了我理解的部份內容,後續還會補充。

 

更多正則的相關內容能夠參考如下文章:

極客學院的學習筆記:

1. python之旅 http://wiki.jikexueyuan.com/project/explore-python/Regular-Expressions/README.html

2. python網絡爬蟲 http://wiki.jikexueyuan.com/project/python-crawler/regular-expression.html

3. 輕鬆學習正則表達式 http://wiki.jikexueyuan.com/project/regex/introduction.html

4. python正則表達式指南 http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

 

最後,推薦一個更強大的正則表達式引擎-python的regex模塊。

相關文章
相關標籤/搜索