python re 正則表達式學習總結
- 2020 年 1 月 13 日
- 筆記
# -*- coding: utf-8 -*- import re import os #------------------------------------- re(正則表達式)模組 -------------------------------- #----------------------------------------------------------------------------------------------------- #------------------------------------- 概念 -------------------------------- #----------------------------------------------------------------------------------------------------- ''' 正則表達式:又稱正規表示法、常規表示法(英語:Regular Expression,在程式碼中常簡寫為regex、regexp或RE), 電腦科學的一個概念。正則表達式使用單個字元串來描述、匹配一系列符合某個句法規則的字元串。在很多文本編輯器里, 正則表達式通常被用來檢索、替換那些符合某個模式的文本。 Python通過re模組提供對正則表達式的支援。使用re的一般步驟是先使用re.compile()函數,將正則表達式的字元串形式編譯為Pattern實例, 然後使用Pattern實例處理文本並獲得匹配結果(一個Match實例),最後使用Match實例獲得資訊,進行其他的操作。 ''' #----------------------------------------------------------------------------------------------------- #------------------------------------- 元字元 -------------------------------- #----------------------------------------------------------------------------------------------------- ''' 元字元(Meta-Characters)是正則表達式中具有特殊意義的專用字元,用來規定其前導字元(即位於元字元前面的字元)在目標對象中的出現模式。 . 表示任意字元 [] 用來匹配一個指定的字元類別,所謂的字元類別就是你想匹配的一個字符集,對於字符集中的字元可以理解成或的關係。 ^ 如果放在字元串的開頭,則表示取非的意思。[^5]表示除了5之外的其他字元。而如果^不在字元串的開頭,則表示它本身。 可以看成轉意字元(同C語言) | 表示或 左右表達式各任意匹配一個,從左邊先匹配起,如果成功,則跳過右邊的表達式.如果沒有放在()中,則範圍是整個表達式 具有重複功能的元字元 * 對於前一個字元重複"0~無窮"次 + 對於前一個字元,重複"1~無窮"次 ? 對於前一個字元,重複"0~1"次 {m,n} 對於前一個字元,重複"m~n"次,其中{0,}等價於*, {1,}等價於+, {0,1}等價於? {m,n}? 對前一個字元,重複"m~n"次,非貪婪模式 {m} 對前一個字元,重複"m"次 d 匹配十進位數, 等價於[0-9] D 匹配任意非數字字元, 等價於[^0-9] s 匹配任何空白字元, 等價於[<空格>fnrtv] S 匹配任何非空白字元, 等價於[^<空格>fnrtv] w 匹配任意單詞字元(構成單詞的字元,字母,數字,下劃線), 等價於[a-zA-Z0-9_] W 匹配任意非單詞字元(構成單詞的字元,字母,數字,下劃線), 等價於[^a-zA-Z0-9_] A 匹配字元串的開頭 Z 匹配字元串的結尾 以下是(?...)系列 這是一個表達式的擴展符號。'?'後的第一個字母決定了整個表達式的語法和含義,除了(?P...)以外,表達式不會產生一個新的組。 (?iLmsux) 'i'、'L'、'm'、's'、'u'、'x'里的一個或多個字母。表達式不匹配任何字元,但是指定相應的標誌:re.I(忽略大小寫)、re.L(依賴locale)、re.M(多行模式)、re.S(.匹配所有字元)、re.U(依賴Unicode)、re.X(詳細模式)。 (?P<name>...) 除了原有的編號外再額外指定一個別名 (?P=name...) 引用別名name分組找到的字元串 (?#...) #後面的將被作為注釋, 相當於表達式中的注釋 (?:...) 匹配內部的RE所匹配的內容,但是不建立組。 (?=...) 如果 ... 匹配接下來的字元,才算匹配,但是並不會消耗任何被匹配的字元,這個叫做「前瞻斷言」。 (?!...) 如果 ... 不匹配接下來的字元,才算匹配, 和(?=...)相反 (?<=...) 只有噹噹前位置之前的字元串匹配 ... ,整個匹配才有效,這叫「後顧斷言」。 (?<!...) 只有噹噹前位置之前的字元串不匹配 ...,整個匹配才有效, 和(?<=...)相反 ''' #-------------------- . ----------------- """ . 在默認模式下,匹配除換行符外的所有字元。在DOTALL模式下,匹配所有字元,包括換行符。 """ s = 'hellonworld!' m = re.findall('.', s) print(m) #['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '!'] m1 = re.findall('.', s, re.DOTALL) print(m1) #['h', 'e', 'l', 'l', 'o', 'n', 'w', 'o', 'r', 'l', 'd', '!'] s2 = '' m2 = re.findall('.', s2, re.DOTALL) print(m2) #[] #-------------------- [] ----------------- s = 'hello world!' m = re.findall('[adf]', s) #字符集表示法, 匹配a或d或f的字元 print(m) #['d'] n = re.findall('[a-e]', s) #區間表示法, 匹配a~e的字元 print(n) #['e', 'd'] #-------------------- ^ ----------------- """ ^ "^abc" 放在字元串abc的開頭表示匹配以abc開始的字元串 "ab^c" 暫時不明 "abc^" 暫時不明 [^abc] 放在[]中的開頭表示取反, 表示非abc之外的其它字元 [ab^c] 中的非開頭表示普通字元^ [abc^] 放在在[]內尾位,就只代表普通字元^ """ s = 'hello world! [^_^]' m = re.findall('^hel', s) print(m) #['hel'] m1 = re.findall('h^el', s) print(m1) #[] m2 = re.findall('hel^', s) print(m2) #[] m3 = re.findall('[^hel]', s) print(m3) #['o', ' ', 'w', 'o', 'r', 'd', '!', ' ', '[', '^', '_', '^', ']'] m4 = re.findall('[h^el]', s) print(m4) #['h', 'e', 'l', 'l', 'l', '^', '^'] m5 = re.findall('[hel^]', s) print(m5) #['h', 'e', 'l', 'l', 'l', '^', '^'] #-------------------- ----------------- """ 轉意字元 """ s = 'hello world!^_^' m = re.findall('[^a-h]', s) #匹配非a~h的所有字元 print(m) #['l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', '!', '^', '_', '^'] m1 = re.findall('[^a-h]', s) #^被轉意了,使之變成了普通字元的意思, 匹配非a~h和^字元 print(m1) #['h', 'e', 'd', '^', '^'] #-------------------- * ----------------- """ * 匹配0~無窮個前面的字元, 如何只想匹配*字元,可以寫*或者[*], *等價於[*] """ s = 'hello world! yes! ^_^' m = re.findall('el*', s) #匹配el(l數量為0~無窮) print(m) #['ell', 'e'] s = '*****hello***' m = re.findall('[*]*', s) #匹配查找**字元串 print(m) #['**', '**', '**'] #-------------------- ? ----------------- """ ? 匹配0~1個前面的字元 """ s = 'hello world! yes! ^_^' m = re.findall('el?', s) #匹配el(l數量為0~1) print(m) #['el', 'e'] #-------------------- + ----------------- """ + 匹配1~無窮個前面的字元 """ s = 'hello world! yes! ^_^' m = re.findall('el+', s) #匹配el(l數量為1~無窮) print(m) #['el'] #-------------------- | ----------------- """ | 表示或 左右表達式各任意匹配一個,從左邊先匹配起,如果成功,則跳過右邊的表達式.如果沒有放在()中,則範圍是整個表達式 """ s = 'hello world! yes! ^_^' m = re.findall("e|o", s) print(m) #['e', 'o', 'o', 'e'] #-------------------- {} ----------------- """ {m} 表示前面的正則表達式m次copy {m} 表示前面的正則表達式m次copy, 由於只有一個m,所以等價於{m}?, 所以一般不這麼寫 {m,n} 表示前面的正則表達式m~n次copy, 嘗試匹配儘可能多的copy {m,n}? 表示前面正則表達式的m到n次copy,嘗試匹配儘可能少的copy """ s = 'hello world! yes! ^_^' m = re.findall("e{0,}l{1,6}o{1}", s) print(m) #['ell', 'l'] s = 'aaaaaaa' m = re.findall('a{2}', s) print(m) #['aa', 'aa'] m = re.findall('a{2}?', s) print(m) #['aa', 'aa'] m = re.findall('a{2,5}', s) print(m) #['aaaaa', 'aa'] m = re.findall('a{2,5}?', s) print(m) #['aa', 'aa', 'aa'] #-------------------- () ----------------- """ () 表示一組, 同C語言 """ s = 'hello world! yes! ^_^' m = re.findall('[(l+)|(es)]', s) #匹配el(l數量為0~無窮) print(m) #['e', 'l', 'l', 'l', 'e', 's'] #-------------------- $ ----------------- """ $ 匹配字元串末尾,在多行(MULTILINE)模式中,匹配每一行的末尾. """ s = 'hello foo1nworld foo2n' m = re.findall('foo.$', s) #匹配以foo.結尾的字元串foo. print(m) #['foo2'] s = 'hello foo1nworld foo2n' m = re.findall('foo.$', s, re.M) #多行模式re.M下, 匹配每行以foo.結尾的字元串foo. print(m) #['foo1', 'foo2'] #-------------------- A ----------------- """ A 匹配字元串開始. """ s = 'hello world' m = re.findall('Ahell', s) print(m) #['hell'] m = re.findall('Aell', s) print(m) #[] #-------------------- Z ----------------- """ Z 匹配字元串結尾. """ s = 'hello world' m = re.findall('ldZ', s) print(m) #['ld'] m = re.findall('orlZ', s) print(m) #[] #-------------------- (?P<name>...) ----------------- """ (?P<name>...) 除了原有的編號外再額外指定一個別名 """ m = re.match("(?P<first>w+) (?P<second>w+)", "hello world") #匹配到第1個起別名'first',匹配到第2個起別名second g = m.groupdict() print(g) #{'second': 'world', 'first': 'hello'} print(g['first']) #hello #-------------------- number ----------------- """ number 引用編號為number的分組找到的字元串 """ m = re.findall('(d)he(d)llo(d)', '1he5llo2 3world4, 1he5llo5 3world4') print(m) #[('1', '5', '2'), ('1', '5', '5')] m = re.findall('dhedllo2', '1he5llo2 3world4, 1he5llo5 3world4') print(m) #[] #-------------------- (?iLmsux) ----------------- """ 'i'、'L'、'm'、's'、'u'、'x'里的一個或多個字母。表達式不匹配任何字元,但是指定相應的標誌: re.I(忽略大小寫)、re.L(依賴locale)、re.M(多行模式)、re.S(.匹配所有字元)、re.U(依賴Unicode)、re.X(詳細模式)。 """ s = 'hello foo1nworld foo2n' m = re.findall('foo.$', s) print(m) #['foo2'] m = re.findall('(?m)foo.$', s) #等價於m = re.findall('foo.$', s, re.M) print(m) #['foo1', 'foo2'] s1 = 'HELLO WORLD' m = re.findall('(?i)[a-z]', s1) #等價於m = re.findall('[a-z]', s, re.) print(m) #['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D'] #-------------------- (?P=name...) ----------------- """ (?P=name...) 引用別名name分組找到的字元串 """ #匹配到第1個起別名'first'+空格+匹配到第2個起別名second+逗號+別名first找到的結果作為搜索表達式的一部分 m = re.match("(?P<first>w+) (?P<second>w+),(?P=first)", "hello world,hello world") g = m.groupdict() print(g) #{'second': 'world', 'first': 'hello'} m = re.match("(?P<first>w+) (?P<second>w+) (?P<third>(?P=first))", "hello world hello world") g = m.groupdict() print(g) #{'second': 'world', 'third': 'hello', 'first': 'hello'} #-------------------- (?#...) ----------------- """ (?#...) #後面的將被作為注釋, 相當於表達式中的注釋 """ s = 'hello1 #12345' m = re.findall('hew+d', s) print(m) #['hello1'] m = re.findall('hew+(?#前面這個表達式hew+意思是he和任意單詞字元的組合)d', s) print(m) #['hello1'] #-------------------- (?=...) ----------------- """ (?=...) 如果 ... 匹配接下來的字元,才算匹配,但是並不會消耗任何被匹配的字元。 例如 Isaac (?=Asimov) 只會匹配後面跟著 'Asimov' 的 'Isaac ',這個叫做「前瞻斷言」。 """ s = 'hellooookl world, help' g = re.findall('hel', s) print(g) #['hel', 'hel'] g = re.findall('hel(?=lo)', s) #遍歷查找hel, (?=lo)位置跟著lo的才算 print(g) #['hel'] #-------------------- (?!...) ----------------- """ (?!...) 和 (?!=...)正好相反。 """ s = 'hello world, help' g = re.findall('hel(?!lo)', s) #遍歷查找hel, (?=lo)位置沒有跟著lo的才算 print(g) #['hel'] g = re.findall('hel(?!klo)', s) #遍歷查找hel, (?=klo)位置沒有跟著klo的才算 print(g) #['hel', 'hel'] #-------------------- (?<=...) ----------------- """ (?<=...) 只有噹噹前位置之前的字元串匹配 ... ,整個匹配才有效,這叫「後顧斷言」。 """ s = 'hhello world, hkelp' g = re.findall('el', s) #遍歷查找el print(g) #['el', 'el'] g = re.findall('(?<=h)el', s) #遍歷查找el, (?<=h)位置跟著h的才算 print(g) #['el'] #-------------------- (?<!...) ----------------- """ (?<!...) 只有噹噹前位置之前的字元串不匹配 ... ,整個匹配才有效,和(?<=...)功能相反. """ s = 'hello world, hkelp' g = re.findall('el', s) #遍歷查找el print(g) #['el', 'el'] g = re.findall('(?<!h)el', s) #遍歷查找el,(?<!h)的位置沒有跟著h的才算 print(g) #['el'] g = re.findall('(?<!m)el', s) #遍歷查找el, (?<!m)的位置沒有跟著m的才算 print(g) #['el', 'el'] #----------------------------------------------------------------------------------------------------- #------------------------------------- 數量詞的貪婪模式與非貪婪模式 -------------------------------- #----------------------------------------------------------------------------------------------------- """ 正則表達式通常用於在文本中查找匹配的字元串。Python里數量詞默認是貪婪的(在少數語言里也可能是默認非貪婪), 總是嘗試匹配儘可能多的字元;非貪婪的則相反,總是嘗試匹配儘可能少的字元。例如:正則表達式"ab*"如果用於查找"abbbc", 將找到"abbb"。而如果使用非貪婪的數量詞"ab*?",將找到"a"。 """ s = 'abbbbb' g = re.findall('ab+', s) print(g) #['abbbbb'] g = re.findall('ab+?', s) print(g) #['ab'] #----------------------------------------------------------------------------------------------------- #------------------------------------- 反斜杠 -------------------------------- #----------------------------------------------------------------------------------------------------- """ 與大多數程式語言相同,正則表達式里使用""作為轉義字元,這就可能造成反斜杠困擾。假如你需要匹配文本中的字元"", 那麼使用程式語言表示的正則表達式里將需要4個反斜杠"\\":前兩個和後兩個分別用於在程式語言里轉義成反斜杠, 轉換成兩個反斜杠後再在正則表達式里轉義成一個反斜杠。Python里的原生字元串很好地解決了這個問題,這個例子中的正則表達式可以使用r"\"表示。 同樣,匹配一個數字的"\d"可以寫成r"d"。有了原生字元串,你再也不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀。 """ s = 'abc12\df3g4h' pattern = r'd\' pattern_obj = re.compile(pattern) g = re.findall(pattern_obj, s) print(g) #['2\'] #----------------------------------------------------------------------------------------------------- #------------------------------------- 函數部分 -------------------------------- #----------------------------------------------------------------------------------------------------- #-------------------- re.compile(strPattern[, flag]) ----------------- """ re.compile(strPattern[, flag]): 這個方法是Pattern類的工廠方法,用於將字元串形式的正則表達式編譯為Pattern對象。 第二個參數flag是匹配模式,取值可以使用按位或運算符'|'表示同時生效,比如re.I | re.M。 另外,你也可以在regex字元串中指定模式,比如re.compile('pattern', re.I | re.M)與re.compile('(?im)pattern')是等價的。 可選值有: re.I(re.IGNORECASE): 忽略大小寫(括弧內是完整寫法,下同) M(MULTILINE): 多行模式,改變'^'和'$'的行為(參見上圖) S(DOTALL): 點任意匹配模式,改變'.'的行為 L(LOCALE): 使預定字元類 w W b B s S 取決於當前區域設定 U(UNICODE): 使預定字元類 w W b B s S d D 取決於unicode定義的字元屬性 X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字元,並可以加入注釋。以下兩個正則表達式是等價的: a = re.compile(r'''d + # the integral part . # the decimal point d * # some fractional digits''', re.X) b = re.compile(r"d+.d*") re提供了眾多模組方法用於完成正則表達式的功能。這些方法可以使用Pattern實例的相應方法替代,唯一的好處是少寫一行re.compile()程式碼, 但同時也無法復用編譯後的Pattern對象。如下面這個例子可以簡寫為: """ s = 'hello world' p = re.compile('hello') match = re.match(p, s) if match: print(match.group()) #hello #上面例子等價於(可以簡寫為) match = re.match('hello', 'hello world') print(match.group()) #hello #-------------------- re.match(pattern, string, flags=0) ----------------- """ Match對象是一次匹配的結果,包含了很多關於此次匹配的資訊,可以使用Match提供的可讀屬性或方法來獲取這些資訊。 屬性: string: 匹配時使用的文本。 re: 匹配時使用的Pattern對象。 pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。 endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。 lastindex: 最後一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將為None。 lastgroup: 最後一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將為None。 方法: group([group1, …]): 獲得一個或多個分組截獲的字元串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時, 返回group(0);沒有截獲字元串的組返回None;截獲了多次的組返回最後一次截獲的子串。 groups([default]): 以元組形式返回全部分組截獲的字元串。相當於調用group(1,2,…last)。default表示沒有截獲字元串的組以這個值替代,默認為None。 groupdict([default]): 返回以有別名的組的別名為鍵、以該組截獲的子串為值的字典,沒有別名的組不包含在內。default含義同上。 start([group]): 返回指定的組截獲的子串在string中的起始索引(子串第一個字元的索引)。group默認值為0。 end([group]): 返回指定的組截獲的子串在string中的結束索引(子串最後一個字元的索引+1)。group默認值為0。 span([group]): 返回(start(group), end(group))。 expand(template): 將匹配到的分組代入template中然後返回。template中可以使用id或g<id>、g<name>引用分組,但不能使用編號0。id與g<id>是等價的; 但10將被認為是第10個分組,如果你想表達1之後是字元'0',只能使用g<1>0。 """ match = re.match(r'(w+) (w+)(?P<sign>.*)', 'hello world!') print(match.string) #hello world! print(match.re) #<_sre.SRE_Pattern object at 0x100298e90> print(match.pos) #0 print(match.endpos) #12 print(match.lastindex) #3 print(match.lastgroup) #sign print(match.groups()) #('hello', 'world', '!') print(match.group(0)) #hello world! print(match.group(1, 2)) #('hello', 'world') print(match.groupdict()) #{'sign': '!'} print(match.start(2)) #6 print(match.end(2)) #11 print(match.span(2)) #(6, 11) print(match.expand(r'2 13')) #world hello! #-------------------- re.search(pattern, string, flags=0) ----------------- """ search對象是一次匹配的結果 屬性和方法同re.match(pattern, string, flags=0),它倆的區別: match()函數只檢測RE是不是在string的開始位置匹配, search()會掃描整個string查找匹配; 也就是說match()只有在0位置匹配成功的話才有返回, 如果不是開始位置匹配成功的話,match()就返回none。 """ s = 'hello world, hellp' print(re.match('hel', s).span()) #(0, 3) print(re.match('ell', s)) #None print(re.search('hel', s).span()) #(0, 3) print(re.search('ell', s).span()) #(1, 4) #-------------------- Pattern相關實例方法 ----------------- """ Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。 Pattern不能直接實例化,必須使用re.compile()進行構造。 Pattern提供了幾個可讀屬性用於獲取表達式的相關資訊: pattern: 編譯時用的表達式字元串。 flags: 編譯時用的匹配模式。數字形式。 groups: 表達式中分組的數量。 groupindex: 以表達式中有別名的組的別名為鍵、以該組對應的編號為值的字典,沒有別名的組不包含在內。 """ p = re.compile(r'(w+) (w+)(?P<sign>.*)', re.I) print(p.pattern) #(w+) (w+)(?P<sign>.*) print(p.flags) #2 print(p.groups) #3 print(p.groupindex) #{'sign': 3} #-------------------- match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]) ----------------- """ match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]): 這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。 pos和endpos的默認值分別為0和len(string);re.match()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。 注意:這個方法並不是完全匹配。當pattern結束時若string還有剩餘字元,仍然視為成功。想要完全匹配,可以在表達式末尾加上邊界匹配符'$'。 """ s = 'hello world, help' p = re.compile('hel') m = p.match(s, 0, 10) print(m.group()) #hel m = p.match(s) print(m.group()) #hel m = re.match('hel', s) print(m.group()) #hel #-------------------- search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]) ----------------- """ 2.search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 這個方法用於查找字元串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象; 若無法匹配,則將pos加1後重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。 pos和endpos的默認值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。 """ s = 'hello world, help' p = re.compile('hel') m = p.search(s, 0, 10) print(m.group()) #hel m = p.search(s) print(m.group()) #hel m = re.search('hel', s) print(m.group()) #hel #-------------------- split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]) ----------------- """ split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。 """ p = re.compile(r'd+') print(p.split('one1two2three3four4')) #['one', 'two', 'three', 'four', ''] print(p.split('one1two2three3four4', 2)) #['one', 'two', 'three3four4'] print(re.split(r'd+','one1two2three3four4')) #['one', 'two', 'three', 'four', ''] print(re.split(r'd+', 'one1two2three3four4', 2)) #['one', 'two', 'three3four4'] #-------------------- findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]) ----------------- """ findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 搜索string,以列表形式返回全部能匹配的子串。re中的findall無法指定字元串搜索起止位置, pattern中的findall無法指定標記類型 """ p = re.compile(r'd+') print(p.findall('one1two2three3four4')) #['1', '2', '3', '4'] print(p.findall('one1two2three3four4', 10)) #['3', '4'] print(re.findall(r'd+','one1two2three3four4')) #['1', '2', '3', '4'] print(re.findall(r'd+', 'one1two2three3four4', re.I)) #['1', '2', '3', '4'] #-------------------- finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]) ----------------- """ finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。re中的findall無法指定字元串搜索起止位置, pattern中的findall無法指定標記類型 """ p = re.compile(r'd+') for m in p.finditer('one1two2three3four4'): print(m.group()) #1 #2 #3 #4 for m in p.finditer('one1two2three3four4', 0, 10): print(m.group()) #1 #2 for m in re.finditer(p, 'one1two2three3four4'): print(m.group()) #1 #2 #3 #4 #-------------------- sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]) ----------------- """ sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 使用repl替換string中每一個匹配的子串後返回替換後的字元串。 當repl是一個字元串時,可以使用id或g<id>、g<name>引用分組,但不能使用編號0。 當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字元串用於替換(返回的字元串中不能再引用分組)。 count用於指定最多替換次數,不指定時全部替換。 """ p = re.compile(r'(w+) (w+)') s = 'i say, hello world!' m = re.search(p, s) print(p.sub(r'2 1', s)) #say i, world hello! def func(x): return x.group(1).title() + ' ' + x.group(2).title() print(p.sub(func, s)) #I Say, Hello World! #-------------------- subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]) ----------------- """ subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]): 返回 (sub(repl, string[, count]), 替換次數) """ p = re.compile(r'(w+) (w+)') s = 'i say, hello world!' m = re.search(p, s) print(p.subn(r'2 1', s)) #('say i, world hello!', 2) def func(x): return x.group(1).title() + ' ' + x.group(2).title() print(p.subn(func, s)) #('I Say, Hello World!', 2)
在網上查閱引用了一些資料,順帶著的練習與總結,新手上路,不足之處多多指正