python基礎-- 正則表達式

 

正則表達式是對字符串操做的一種邏輯公式,python

正則表達式是用來匹配字符串很是強大的工具,正則表達式

    正則表達式的大體匹配過程是:
    1.依次拿出表達式和文本中的字符比較,
    2.若是每個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。
    3.若是表達式中有量詞或邊界,這個過程會稍微有一些不一樣。函數

 

正則表達式符號含義:

    re表明正則表達式:工具

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

實例:spa

  正則在python的的調用方法有兩種,.net

  一種是使用re.compile(r, f)方法生成正則表達式對象,而後調用正則表達式對象的相應方法。這種作法的好處是生成正則對象以後能夠屢次使用。code

  另外一種是直接用類方法調用;對象

  

1
2
3
4
5
6
7
8
9
10
#返回pattern對象
re. compile (string[,flag])
#如下爲匹配所用函數
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])

  

正則有的主要的四大功能:    

    1. 匹配 查看一個字符串是否符合正則表達式的語法,通常返回true或者false
    2. 獲取 正則表達式來提取字符串中符合要求的文本
    3. 替換 查找字符串中符合正則表達式的文本,並用相應的字符串替換
    4. 分割 使用正則表達式對字符串進行分割。blog

1.re.findall(s,start, end):搜索string,以列表形式返回所有能匹配的子串。
pattern = re.compile(r'\d+')
print re.findall(pattern,'one1two2three3four4')
  
### 輸出 ###
# ['1', '2', '3', '4']

 

 
2. re.finditer(s, start, end):
搜索string,返回一個順序訪問每個匹配結果(Match對象)的迭代器。
import re
  
pattern = re.compile(r'\d+')
for m in re.finditer(pattern,'one1two2three3four4'):
  print m.group(),
  
### 輸出 ###
# 1 2 3 4

 

 
3. re.search(s, start, end):
search方法與match方法極其相似,區別在於match()函數只檢測re是否是在string的開始位置匹配,search()會掃描整個string查找匹配,match()只有在0位置匹配成功的話纔有返回,若是不是開始位置匹配成功的話,match()就返回None。一樣,search方法的返回對象一樣match()返回對象的方法和屬性。
# 將正則表達式編譯成Pattern對象
pattern = re.compile(r'world')
# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None
# 這個例子中使用match()沒法成功匹配
match = re.search(pattern,'hello world!')
if match:
  # 使用Match得到分組信息
  print match.group()
### 輸出 ###
# world

 

 
 
4. re.match(s, start, end):這個方法將會從string(咱們要匹配的字符串)的開頭開始,嘗試匹配pattern,一直向後匹配,若是遇到沒法匹配的字符,當即返回 None,若是匹配未結束已經到達string的末尾,也會返回None。兩個結果均表示匹配失敗,不然匹配pattern成功,同時匹配終止,再也不對 string向後匹配。
# 匹配以下內容:單詞+空格+單詞+任意字符
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!

 

 
5.  re.sub(pattern, repl, string[, count])
使用repl替換string中每個匹配的子串後返回替換後的字符串。
當repl是一個字符串時,可使用\id或\g、\g引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。
count用於指定最多替換次數,不指定時所有替換。
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!

 

 
6. re.subn(x, s, m):
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)

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

按照可以匹配的子串將string分割後返回列表

import re
  
pattern = re.compile(r'\d+')
print re.split(pattern,'one1two2three3four4')
  
### 輸出 ###
# ['one', 'two', 'three', 'four', '']

 

   匹配結果對象的屬性方法:

    01. m.group(g, ...)
      返回編號或者組名匹配到的內容,默認或者0表示整個表達式匹配到的內容,若是指定多個,就返回一個元組
    02. m.groupdict(default)
      返回一個字典。字典的鍵是全部命名的組的組名,值爲命名組捕獲到的內容
      若是有default參數,則將其做爲那些沒有參與匹配的組的默認值。
    03. m.groups(default)
      返回一個元組。包含全部捕獲到內容的子分組,從1開始,若是指定了default值,則這個值做爲那些沒有捕獲到內容的組的值
    04. m.lastgroup()
      匹配到內容的編號最高的捕獲組的名稱,若是沒有或者沒有使用名稱則返回None(不經常使用)
    05. m.lastindex()
      匹配到內容的編號最高的捕獲組的編號,若是沒有就返回None。
    06. m.start(g):
      當前匹配對象的子分組是從字符串的那個位置開始匹配的,若是當前組沒有參與匹配就返回-1
    07. m.end(g)
      當前匹配對象的子分組是從字符串的那個位置匹配結束的,若是當前組沒有參與匹配就返回-1
    08. m.span()
      返回一個二元組,內容分別是m.start(g)和m.end(g)的返回值
    09. m.re()
      產生這一匹配對象的正則表達式
    10. m.string()
      傳遞給match或者search用於匹配的字符串
    11. m.pos()
      搜索的起始位置。即字符串的開頭,或者start指定的位置(不經常使用)
    12. m.endpos()
      搜索的結束位置。即字符串的末尾位置,或者end指定的位置(不經常使用)

 

 

 

難點:

1 分組 

在re.findall() 方法裏面,若是正則表達式裏面有(),則返回括號部分的匹配結果

實例

 

1 不加括號
print(re.findall('a+\d+\w+','aaaa1111aaaa,aaa222aa,nnn22cc'))
輸出 ['aaaa1111aaaa', 'aaa222aa']
2 加括號
print(re.findall('a+(\d+)\w+','aaaa1111aaaa,aaa222aa,nnn22cc'))
輸出 ['1111', '222']

2 斷言

https://blog.csdn.net/magictong/article/details/5332423

相關文章
相關標籤/搜索