自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一日一技:讓你的正則表達式可讀性提高一百倍

開發(fā)
有沒有什么辦法提高正則表達式的可讀性呢?我們知道,提高代碼可讀性的方法之一就是寫注釋,那么正則表達式能不能寫注釋呢?

正則表達式這個東西,強大是強大,但寫出來跟個表情符號一樣。自己寫的表達式,過一個月來看,自己都不記得是什么意思了。比如下面這個:

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])|$)"

有沒有什么辦法提高正則表達式的可讀性呢?我們知道,提高代碼可讀性的方法之一就是寫注釋,那么正則表達式能不能寫注釋呢?

例如對于下面這個句子:

msg = '我叫青南,我的密碼是:123kingname456,請注意保密。'

我要提取其中的密碼123kingname456,那么我的正則表達式可能是這樣的:

pattern = ':(.*?),'

我能不能把它寫成這樣:

pattern = '''
: # 開始標志
(.*?) #從開始標志的下一個字符開始的任意字符
, #遇到英文逗號就停止
'''

這樣寫就清晰多了,每個部分是什么作用全都清清楚楚。

但顯然直接使用肯定什么都提取不到,如下圖所示:

圖片

但我今天在逛Python正則表達式文檔的時候,發(fā)現(xiàn)了一個好東西:

圖片

使用它,可以讓你的正則表達式擁有注釋,如下圖所示:

圖片

re.VERBOSE?也可以簡稱為re.X,如下圖所示:

圖片

本文最開頭的復(fù)雜正則表達式,使用了注釋以后,就會變得更可讀:

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
| $
)
"""
責(zé)任編輯:趙寧寧 來源: 未聞Code
相關(guān)推薦

2021-06-15 20:56:39

Python正則表達式

2020-12-17 06:22:57

交互模式代碼

2024-08-27 22:08:13

2021-04-27 22:15:02

Selenium瀏覽器爬蟲

2022-01-26 07:35:10

爬蟲Requestsgzip

2021-10-11 20:02:49

Python父類方法

2021-10-15 21:08:31

PandasExcel對象

2022-06-28 09:31:44

LinuxmacOS系統(tǒng)

2021-04-05 14:47:55

Python多線程事件監(jiān)控

2024-11-13 09:18:09

2022-03-12 20:38:14

網(wǎng)頁Python測試

2021-03-18 23:28:45

Python反斜杠字符串

2021-04-12 21:19:01

PythonMakefile項目

2022-06-09 21:34:41

Python代碼函數(shù)

2024-12-27 00:44:44

MarkdownPrompt大模型

2018-09-27 15:25:08

正則表達式前端

2023-10-28 12:14:35

爬蟲JavaScriptObject

2021-03-12 21:19:15

Python鏈式調(diào)用

2024-07-30 08:16:18

Python代碼工具

2021-09-13 20:38:47

Python鏈式調(diào)用
點贊
收藏

51CTO技術(shù)棧公眾號