re中通常用''區分自定義字符,這個與在字符傳中相同的字母和目的的字符串衝突,e.g.'\\'用來表示"\",由於每一個''都是"\"
解決方法: re中用r表示raw string.也就是說r"\n"表明''和'n'這兩個字符python
re.escape(pattern) 忽略在pattern中的某些特定的字符, 也就是說不包含metacharacter(在計算機中有特定含義的字符,例如\,*,+,(,{,|,^,$等) e.g. (python3.6) >>> import re >>> re.escape('^a.*s') '\\^a\\.\\*s' >>> re.escape('python.exe') 'python\\.exe' 在py3.3以後,'_'不會被escaped,也就是說,下面這兩種sub的表達方式一致: >>> re.sub('a', re.escape('_'), 'aa') '__' >>> re.sub('a', lambda _:'_', 'aa') '__' >>> *可是,與sub()和subn(),escape通常不用在中間
re.I: 表明忽略大小寫
re.compile(pattern,flags=0):將正則表達模式編譯成一個正則表達對象, 這個對象能夠用在match(),search()或者其餘方法中進行匹配. prog = re.compile(pattern) result=prog.match(string) 與 result=re.match(pattern, string) 等價 可是,當同一個模式屢次匹配的時候,上面的compile方式會更有效率
re.finditer(pattern, string, flags=0) or pattern_object.finditer(string, flags=0) 返回一個iterator,爲string中沒有重疊的匹配pattern的match objects, 傳回順序爲string由左到右按照順序匹配的順序
Match.start([group]) 返回該group匹配的子字符串的起始未知的位置index, group參數默認爲0,也就是整個匹配的字符串 Match.end([group])同理,返回的是結束未知的index >>> email = "tony@tiremove_thisger.net" >>> m = re.search("remove_this", email) >>> email[:m.start()] + email[m.end():] 'tony@tiger.net'