python re模塊中re.S, re.U, re.I, re.M, re.X

修飾符 描述
re.I 忽略大小寫
re.L 做本地化識(shí)別(locale-aware)匹配
re.M 多行匹配,影響 ^ 和 $
re.S 即為 . 并且包括換行符在內(nèi)的任意字符(. 不包括換行符)
re.U 根據(jù)Unicode字符集解析字符。這個(gè)標(biāo)志影響 \w, \W, \b, \B
re.X 為了增加可讀性,忽略空格和 # 后面的注釋

re.I

忽略待匹配字符串的大小寫

In[2]: re.findall("dream", "I HAVE A DREAM")
Out[2]: []
In[3]: re.findall("dream", "I HAVE A DREAM", re.I)
Out[3]: ['DREAM']

re.L

做本地化local識(shí)別,python中有個(gè)locale模塊,locale代表不同的語言,地區(qū)和字符集

In[2]: re.L
Out[2]: <RegexFlag.LOCALE: 4>

re.M

多行匹配,影響 ^ 和 $

In[2]: text='''10-1
11-2'''
In[3]: re.findall(r'[0-9]$', text, re.M)
Out[3]: ['1', '2']
In[4]: re.findall(r'[0-9]$', text)
Out[4]: ['2']
In[5]: re.findall(r'^[0-9]+', text)
Out[5]: ['10']
In[6]: re.findall(r'^[0-9]+', text, re.M)
Out[6]: ['10', '11']

re.S

將換行符包含進(jìn)“.”

In[2]: text='''10-1
11-2'''
In[3]: re.findall(r'-[0-9]+.[0-9]+-', text)
Out[3]: []
In[4]: re.findall(r'-[0-9]+.[0-9]+-', text, re.S)
Out[4]: ['-1\n11-']

re.U

根據(jù)Unicode字符集解析字符。

re.X

允許在正則表達(dá)式中添加注釋

In[2]: rc = re.compile(r"""
# 以字母開頭
^[a-zA-Z]
# 或者以數(shù)字結(jié)尾
| 
\d$
""", re.X)
In[3]: rc.findall("hello&&world123")
Out[3]: ['h', '3']

混合使用

多個(gè)修飾符可同時(shí)疊加使用

In[2]: text='''I HAVE A
DREAM'''
In[3]: re.findall("^dream", text)
Out[3]: []
In[4]: re.findall("^dream", text, re.I)
Out[4]: []
# 忽略大小寫,同時(shí)開啟多行模式
In[5]: re.findall("^dream", text, re.I | re.M)
Out[5]: ['DREAM']
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容