python re 正則表達式學習總結

# -*- 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 匹配任何空白字符, 等價於[<空格>\f\n\r\t\v]
\S 匹配任何非空白字符, 等價於[^<空格>\f\n\r\t\v]
\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 = 'hello\nworld!'
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 foo1\nworld foo2\n'
m = re.findall('foo.$', s)  #匹配以foo.結尾的字符串foo.
print(m)
#['foo2']

s = 'hello foo1\nworld foo2\n'
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('ld\Z', s)
print(m)
#['ld']

m = re.findall('orl\Z', 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('\dhe\dllo\2', '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 foo1\nworld foo2\n'
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('he\w+\d', s)
print(m)
#['hello1']

m = re.findall('he\w+(?#前面這個表達式he\w+意思是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 \1\3'))
#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)


在網上查閱引用了一些資料,順帶着的練習與總結,新手上路,不足之處多多指正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章