python正則表達式 學習記要

正則表達式

正則表達式的作用無非就是兩個,一個是找到你想要的字符串,一個就是對字符串操作。對字符串操作的前提就是找到字符串,所以正則表達式的重點在於如何找到你想要的字符串。
所以學習正則表達式的一大部分是學習對“你想要的字符串”進行描述,爲了讓計算機能知道。等你描述完畢,計算機(正則表達式引擎)就可以去爲你服務了。再扔給它一大長串字符串,讓它找出你想要的信息吧。
那麼,如何描述你想要的字符串(爲了讓引擎能懂)就是一個重點。描述方法如下:
字符有: . \d(digtal) \D \s(space) \S \w(word) \W
字符集有: [ abxy] [a-c] [ ^ab ]
描述數量: * 任意次 + 正數次 ?最多1次 {m,n} m-n次
描述位置: ^ 開頭 $ 末尾 \A 字符串開頭 \Z 字符串末尾
邏輯關係: | ()
分組匹配: () ()\1 用數字指定分組 ( ?P<> )給分組起名字 ()( ?=id ) 以分組的形式引用分組
若想了解詳情,再附一張詳情表:
正則表達式規則表

Python實現方式

正則表達式只是一種算法級的產品,到了各個語言裏,語言要自己實現。下面簡介python的實現方法。
- re模塊,相當於正則表達式引擎,裏面有各種組件
- 對於用戶的描述信息,有pattern類,可以通過re的compile方法得到實例
- parttern包含如下信息:pattern:你的字符串描述,groups:表達式中的分組數量;
- 有了描述信息,就可以查找了,配有match類用來查找
* match類有如下信息:string:你扔給它的文本,re:你的pattern對象,pos,endpos:你希望在文本的位置中查找,lastindex,lastgroup:你找的字符串的位置或別名,可能爲None。
* match有如下方法用於處理上述信息:
* match方法
* match是re的方法,要帶上pattern;
* match也是pattern的方法

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')

### output ###
# m.string: hello world!
# m.re: <_sre.SRE_Pattern object at 0x016E1A38>
# 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!
  • search方法
  • search是re的方法,要帶上pattern;
  • search也是pattern的方法
  • search返回的結果是bool
  • search用於查找信息很方便
  • 代碼如下
pattern = re.compile(r'world') 

# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None 
# 這個例子中使用match()無法成功匹配 
match = pattern.search('hello world!') 

if match: 
    # 使用Match獲得分組信息 
    print match.group() 

### 輸出 ### 
# world
  • sub函數
  • re有一個,pattern有一個
  • 給它一個repl字符串,將所有想要的替換的位置換成repl
import re

p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'

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

def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()

print p.sub(func, s)

### output ###
# say i, world hello!
# I Say, Hello World!

martch和search的區別
match是從字符串的起點開始做匹配,而search是從字符串做任意匹配。
注意:當正則表達式是’ ^ ‘開頭時,match與search是相同的。match只有當且僅當被匹配的字符串開頭就能匹配 或 從pos參數的位置開始就能匹配 時纔會成功。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章