新聞中心
正則表達(dá)式這個(gè)東西,強(qiáng)大是強(qiáng)大,但寫出來跟個(gè)表情符號(hào)一樣。自己寫的表達(dá)式,過一個(gè)月來看,自己都不記得是什么意思了。比如下面這個(gè):

武陵源網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,武陵源網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為武陵源上1000家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)營(yíng)銷網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的武陵源做網(wǎng)站的公司定做!
pattern = r"((?:\(\s*)?[A-Z]*H\d+[a-z]*(?:\s*\+\s*[A-Z]*H\d+[a-z]*)*(?:\s*[\):+])?)(.*?)(?=(?:\(\s*)?[A-Z]*H\d+[a-z]*(?:\s*\+\s*[A-Z]*H\d+[a-z]*)*(?:\s*[\):+])?(?![^\w\s])|$)"
有沒有什么辦法提高正則表達(dá)式的可讀性呢?我們知道,提高代碼可讀性的方法之一就是寫注釋,那么正則表達(dá)式能不能寫注釋呢?
例如對(duì)于下面這個(gè)句子:
msg = '我叫青南,我的密碼是:123kingname456,請(qǐng)注意保密。'
我要提取其中的密碼123kingname456,那么我的正則表達(dá)式可能是這樣的:
pattern = ':(.*?),'
我能不能把它寫成這樣:
pattern = '''
: # 開始標(biāo)志
(.*?) #從開始標(biāo)志的下一個(gè)字符開始的任意字符
, #遇到英文逗號(hào)就停止
'''
這樣寫就清晰多了,每個(gè)部分是什么作用全都清清楚楚。
但顯然直接使用肯定什么都提取不到,如下圖所示:
但我今天在逛Python正則表達(dá)式文檔的時(shí)候,發(fā)現(xiàn)了一個(gè)好東西:
使用它,可以讓你的正則表達(dá)式擁有注釋,如下圖所示:
re.VERBOSE?也可以簡(jiǎn)稱為re.X,如下圖所示:
本文最開頭的復(fù)雜正則表達(dá)式,使用了注釋以后,就會(huì)變得更可讀:
pattern = r"""
( # code (capture)
# BEGIN multicode
(?: \( \s* )? # maybe open paren and maybe space
# code
[A-Z]*H # prefix
\d+ # digits
[a-z]* # suffix
(?: # maybe followed by other codes,
\s* \+ \s* # ... plus-separated
# code
[A-Z]*H # prefix
\d+ # digits
[a-z]* # suffix
)*
(?: \s* [\):+] )? # maybe space and maybe close paren or colon or plus
# END multicode
)
( .*? ) # message (capture): everything ...
(?= # ... up to (but excluding) ...
# ... the next code
# BEGIN multicode
(?: \( \s* )? # maybe open paren and maybe space
# code
[A-Z]*H # prefix
\d+ # digits
[a-z]* # suffix
(?: # maybe followed by other codes,
\s* \+ \s* # ... plus-separated
# code
[A-Z]*H # prefix
\d+ # digits
[a-z]* # suffix
)*
(?: \s* [\):+] )? # maybe space and maybe close paren or colon or plus
# END multicode
# (but not when followed by punctuation)
(?! [^\w\s] )
# ... or the end
| $
)
"""
文章標(biāo)題:一日一技:讓你的正則表達(dá)式可讀性提高一百倍
分享鏈接:http://m.fisionsoft.com.cn/article/coidcsj.html


咨詢
建站咨詢
