Python3 Re常用方法


常用的功能函數包括:compile、search、match、split、findall(finditer)、sub(subn)

1.compile
re.compile(pattern[, flags])
作用:把正則表達式語法轉化成正則表達式對象

flags定義包括:
re.I:忽略大小寫
re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依賴於當前環境
re.M:多行模式
re.S:' . '並且包括換行符在內的任意字符(注意:' . '不包括換行符)
re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依賴於 Unicode 字符屬性數據庫

2.search
re.search(pattern, string[, flags])
作用:在字符串中查找匹配正則表達式模式的位置,返回 MatchObject 的實例,如果沒有找到匹配的位置,則返回 None。

3.match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函數只在字符串的開始位置嘗試匹配正則表達式,也就是只報告從位置 0 開始的匹配情況,
而 search() 函數是掃描整個字符串來查找匹配。如果想要搜索整個字符串來尋找匹配,應當用 search()。

例子:

import re
r1 = re.compile(r'world')  
if r1.match('helloworld'):
    print 'match succeeds'
else:
    print 'match fails'
if r1.search('helloworld'):
    print 'search succeeds'
else:
    print 'search fails'
###############################
#match fails
#search succeeds

4.split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以將字符串匹配正則表達式的部分割開並返回一個列表

import re
inputStr = 'abc aa;bb,cc | dd(xx).xxx 12.12';
print(re.split(' ',inputStr))
#################################
#['abc', 'aa;bb,cc', '|', 'dd(xx).xxx', '12.12']

5.findall
re.findall(pattern, string[, flags])
findall(string[, pos[, endpos]])
作用:在字符串中找到正則表達式所匹配的所有子串,並組成一個列表返回
例:查找[]包括的內容(貪婪和非貪婪查找)

6.finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
說明:和 findall 類似,在字符串中找到正則表達式所匹配的所有子串,並組成一個迭代器返回。

7.sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
說明:在字符串 string 中找到匹配正則表達式 pattern 的所有子串,用另一個字符串 repl 進行替換。如果沒有找到匹配 pattern 的串,則返回未被修改的 string。
Repl 既可以是字符串也可以是一個函數。

import re

def pythonReSubDemo():
    inputStr = "hello 123,my 234,world 345"
    
    def _add111(matched):
        intStr = int(matched.group("number"))
        _addValue = intStr + 111;
        _addValueStr = str(_addValue)
        return _addValueStr

    replaceStr = re.sub("(?P<number>\d+)",_add111,inputStr,1)
    print("replaceStr=",replaceStr)

if __name__ == '__main__':
    pythonReSubDemo();
#########################################
#hello 234,my 234,world 345

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM