就個人而言,主要用它來做一些複雜字串分析,提取想要的資訊
學習原則:夠用就行,需要的時候在深入
現總結如下:
Regex中特殊的符號:
“.” 表任一字元
“^ ” 表string起始
“$” 表string 結束
“*” “+” “?” 跟在字元後面表示,0個——多個, 1個——多個, 0個或者1個
*?, +?, ?? 合格情況下,匹配的儘可能少//限制*,+,?匹配的貪婪性
{m} 匹配此前的字元,重複m次
{m,n} m到n次,m,n可以省略
舉個例子 ‘a.*b’ 表示a開始,b結束的任一字元串
a{5} 匹配連續5個a
[] 表一系列字元 [abcd] 表a,b,c,d [^a] 表示非a
| A|B 表示A或者B , AB為任意的Regex 另外|是非貪婪的如果A匹配,則不找B
(…) 這個括弧的作用要結合執行個體才能理解, 用於提取資訊
d [0-9]
D 非 d
s 表示Null 字元
S 非Null 字元
w [a-zA-Z0-9_]
W 非 w
一:re的幾個函數
1: compile(pattern, [flags])
根據Regex字串 pattern 和可選的flags 產生Regex 對象
產生Regex 對象(見二)
其中flags有下面的定義:
I 表示大小寫忽略
L 使一些特殊字元集,依賴於當前環境
M 多行模式 使 ^ $ 匹配除了string開始結束外,還匹配一行的開始和結束
S “.“ 匹配包括‘n’在內的任一字元,否則 . 不包括‘n’
U Make w, W, b, B, d, D, s and S dependent on the Unicode character properties database
X 這個主要是表示,為了寫Regex,更可毒,會忽略一些空格和#後面的注釋
其中S比較常用,
應用形式如下
import re
re.compile(……,re.S)
2: match(pattern,string,[,flags])
讓string匹配,pattern,後面分flag同compile的參數一樣
返回MatchObject 對象(見三)
3: split( pattern, string[, maxsplit = 0])
用pattern 把string 分開
>>> re.split(‘W+’, ‘Words, words, words.’)
['Words', 'words', 'words', '']
括弧‘()’在pattern內有特殊作用,請查手冊
4:findall( pattern, string[, flags])
比較常用,
從string內尋找不重疊的符合pattern的運算式,然後返回list列表
5:sub( pattern, repl, string[, count])
repl可以時候字串,也可以式函數
當repl是字串的時候,
就是把string 內符合pattern的子串,用repl替換了
當repl是函數的時候,對每一個在string內的,不重疊的,匹配pattern
的子串,調用repl(substring),然後用傳回值替換substring
>>> re.sub(r’defs+([a-zA-Z_][a-zA-Z_0-9]*)s*(s*):’,
… r’static PyObject*npy_1(void)n{‘,
… ‘def myfunc():’)
‘static PyObject*npy_myfunc(void)n{‘
>>> def dashrepl(matchobj):
… if matchobj.group(0) == ‘-’: return ‘ ‘
… else: return ‘-’
>>> re.sub(‘-{1,2}’, dashrepl, ‘pro—-gram-files’)
‘pro–gram files’
二:Regex對象 (Regular Expression Objects )
產生方式:通過 re.compile(pattern,[flags])回
match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配
pattern的MatchObject(見三)
split( string[, maxsplit = 0])
findall( string[, pos[, endpos]])
sub( repl, string[, count = 0])
這幾個函數和re模組內的相同,只不過是調用形式有點差別
re.幾個函數和 Regex對象的幾個函數,功能相同,但同一程式如果
多次用的這些函數功能,Regex對象的幾個函數效率高些
三:matchobject
通過 re.match(……) 和 re.compile(……).match返回
該對象有如下方法和屬性:
方法:
group( [group1, ...])
groups( [default])
groupdict( [default])
start( [group])
end( [group])
說明這幾個函數的最好方法,就是舉個例子
matchObj = re.compile(r”(?Pd+).(d*)”)
m = matchObj.match(’3.14sss’)
#m = re.match(r”(?Pd+).(d*)”, ’3.14sss’)
print m.group()
print m.group(0)
print m.group(1)
print m.group(2)
print m.group(1,2)
print m.group(0,1,2)
print m.groups()
print m.groupdict()
print m.start(2)
print m.string
輸出如下:
3.14
3.14
3
14
(’3′, ’14′)
(’3.14′, ’3′, ’14′)
(’3′, ’14′)
{‘int’: ’3′}
2
3.14sss
所以group() 和group(0)返回,匹配的整個運算式的字串
另外group(i) 就是Regex中用第i個“()” 括起來的匹配內容
(’3.14′, ’3′, ’14′)最能說明問題了。
字串替換
1.替換所有匹配的子串
用newstring替換subject中所有與Regexregex匹配的子串
result, number = re.subn(regex, newstring, subject)2.替換所有匹配的子串(使用Regex對象)
reobj = re.compile(regex)
result, number = reobj.subn(newstring, subject)字串拆分
1.字串拆分
result = re.split(regex, subject)2.字串拆分(使用正則表示式對象)
reobj = re.compile(regex)
result = reobj.split(subject)匹配
下面列出PythonRegex的幾種匹配用法:
1.測試Regex是否匹配字串的全部或部分
regex=ur"..." #Regex
if re.search(regex, subject):
do_something()
else:
do_anotherthing()
2.測試Regex是否匹配整個字串
regex=ur"...Z" #Regex末尾以Z結束
if re.match(regex, subject):
do_something()
else:
do_anotherthing()
3. 建立一個匹配對象,然後通過該對象獲得匹配細節
regex=ur"..." #Regex
match = re.search(regex, subject)
if match:
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
do_something()
else:
do_anotherthing()
4.擷取Regex所匹配的子串
(Get the part of a string matched by the regex)
regex=ur"..." #Regex
match = re.search(regex, subject)
if match:
result = match.group()
else:
result = ""
5. 擷取擷取的群組所匹配的子串
(Get the part of a string matched by a capturing group)
regex=ur"..." #Regex
match = re.search(regex, subject)
if match:
result = match.group(1)
else:
result = ""
6. 擷取有名組所匹配的子串
(Get the part of a string matched by a named group)
regex=ur"..." #Regex
match = re.search(regex, subject)
if match:
result = match.group("groupname")
else:
result = ""
7. 將字串中所有匹配的子串放入數組中
(Get an array of all regex matches in a string)
result = re.findall(regex, subject)8.遍曆所有匹配的子串
(Iterate over all matches in a string)
for match in re.finditer(r"<(.*?)s*.*?/1>", subject)
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()9.通過Regex字串建立一個Regex對象
(Create an object to use the same regex for many operations)
reobj = re.compile(regex)
10.用法1的Regex對象版本
(use regex object for if/else branch whether (part of) a string can be matched)
reobj = re.compile(regex)
if reobj.search(subject):
do_something()
else:
do_anotherthing()
11.用法2的Regex對象版本
(use regex object for if/else branch whether a string can be matched entirely)
reobj = re.compile(r"Z") #Regex末尾以Z 結束
if reobj.match(subject):
do_something()
else:
do_anotherthing()
12.建立一個Regex對象,然後通過該對象獲得匹配細節
(Create an object with details about how the regex object matches (part of) a string)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
do_something()
else:
do_anotherthing()
13.用Regex對象擷取匹配子串
(Use regex object to get the part of a string matched by the regex)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group()
else:
result = ""
14.用Regex對象擷取擷取的群組所匹配的子串
(Use regex object to get the part of a string matched by a capturing group)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group(1)
else:
result = ""
15.用Regex對象擷取有名組所匹配的子串
(Use regex object to get the part of a string matched by a named group)
reobj = re.compile(regex)
match = reobj.search(subject)
if match:
result = match.group("groupname")
else:
result = ""
16.用Regex對象擷取所有匹配子串並放入數組
(Use regex object to get an array of all regex matches in a string)
reobj = re.compile(regex)
result = reobj.findall(subject)17.通過Regex對象遍曆所有匹配子串
(Use regex object to iterate over all matches in a string)
reobj = re.compile(regex)
for match in reobj.finditer(subject):
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
非貪婪、多行匹配Regex例子
一些regular的tips:
1 非貪婪flag
>>> re.findall(r"a(d+?)", "a23b")
['2']
>>> re.findall(r"a(d+)", "a23b")
['23']注意比較這種情況:
>>> re.findall(r"a(d+)b", "a23b")
['23']
>>> re.findall(r"a(d+?)b", "a23b")
['23']
2 如果你要多行匹配,那麼加上re.S和re.M標誌
re.S:.將會匹配分行符號,預設.不會匹配分行符號
>>> re.findall(r"a(d+)b.+a(d+)b", "a23bna34b")
[]
>>> re.findall(r"a(d+)b.+a(d+)b", "a23bna34b",
re.S)
[('23', '34')]
>>>re.M:^$標誌將會匹配每一行,預設^和$只會匹配第一行
>>> re.findall(r"^a(d+)b", "a23bna34b")
['23']
>>> re.findall(r"^a(d+)b", "a23bna34b", re.M)
['23', '34']但是,如果沒有^標誌,
>>> re.findall(r"a(d+)b", "a23bna23b")
['23', '23']可見,是無需re.M