1. 程式人生 > >Python標準庫 - re

Python標準庫 - re

塊代碼 replace number star 代碼 特殊字符 ini sam expr

編寫代碼時, 經常要匹配特定字符串, 或某個模式的字符串, 一般會借助字符串函數, 或正則表達式完成.


對於正則表達式, 有些字符具有特殊含義, 需使用反斜杠字符'\'轉義, 使其表示本身含義. 如想匹配字符'\', 卻要寫成'\\\\', 很是困擾. Python中Raw string解決了該問題, 只需給'\'加上前綴'r'即可, 如r'\n', 表示'\'和'n'兩個普通字符, 而不是原來的換行. 前綴'r'類似於sed命令的-r(use extended regular expressions)參數.


正則表達式可包括兩部分, 一是正常字符, 表本身含義; 二是特殊字符, 表一類正常字符, 或字符數量...


re模塊提供了諸多方法進行正則匹配.

match Match a regular expression pattern to the beginning of a string.

search Search a string for the presence of a pattern.

sub Substitute occurrences of a pattern found in a string.

subn Same as sub, but also return the number of substitutions made.

split Split a string by the occurrences of a pattern.

findall Find all occurrences of a pattern in a string.

finditer Return an iterator yielding a match object for each match.

purge Clear the regular expression cache.

escape Backslash all non-alphanumerics in a string.


還有compile函數, 其較特殊, 將匹配模式編譯為一個正則表達式對象(RegexObject, _sre.SRE_Pattern), 並返回, 該對象仍然可以使用上述這些函數. 這也從側面說明了, 對於re模塊, 有非編譯和編譯兩種使用方式, 如下所示.

1.

result = re.match(pattern, string)


2.

prog = re.compile(pattern)

result = prog.match(string)


它們達到的效果是相同的, 只是後者暫存了正則表達式對象, 對於某塊代碼中頻繁使用該正則表達式的情形, 後者性能一般會高於前者.



對於match()和search()匹配成功, 會返回一個匹配對象(Match Object, _sre.SRE_Match), 其也有若幹方法, 下面幾個較常用.

group

group([group1, ...]) -> str or tuple.

Return subgroup(s) of the match by indices or names.

For 0 returns the entire match.


groups(...)

groups([default=None]) -> tuple.

Return a tuple containing all the subgroups of the match, from 1.

The default argument is used for groups

that did not participate in the match


end(...)

end([group=0]) -> int.

Return index of the end of the substring matched by group.


start(...)

start([group=0]) -> int.

Return index of the start of the substring matched by group.


至此對re模塊框架性梳理就這樣了, 給出些例子, 對上面的內容總結下.

1.

In [23]: text = "He was carefully disguised but captured quickly by police."


In [24]: re.findall(r"\w+ly", text)

Out[24]: ['carefully', 'quickly']


2.

In [25]: m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")


In [26]: m.group(0)

Out[26]: 'Isaac Newton'


In [27]: m.group(1)

Out[27]: 'Isaac'


In [28]: m.group(2)

Out[28]: 'Newton'


In [29]: m.group(1, 2)

Out[29]: ('Isaac', 'Newton')


3.

In [31]: account = "abcxyz_"


In [32]: replace_regex = re.compile(r'_$')


In [33]: replace_regex.sub(account[0], account)

Out[33]: 'abcxyza'



正則表達式使用中的細節還有很多, 這裏無法盡數, 實踐過程中慢慢體會和總結吧.


Python標準庫 - re