python裡使用正規表示式的組匹配通過名稱自引用

2021-08-10 19:08:35 字數 1581 閱讀 4263

在前學習過正規表示式的組可以通過組號來自引用,看起來使用很簡單的樣子,其實它還是不容易維護的,比如你某一天需要在這個正規表示式裡插入乙個組時,就發現後面的組號全打亂了,因此需要乙個乙個地更改組號,有沒有更容易維護的方式呢?是有的,就是使用組名稱來引用。如下面的例子:

#python 3.6

#蔡軍生

##import re

address = re.compile(

'''# the regular name

(?p\w+)

\s+(([\w.]+)\s+)? # optional middle name or initial

(?p\w+)

\s+<

# the address: [email protected]

(?p(?p=first_name)

\.(?p=last_name)

@([\w\d.]+\.)+ # domain name prefix

(com|org|edu) # limit the allowed top-level domains

)>

''',

re.verbose | re.ignorecase)

candidates = [

u'cai junsheng ',

u'different name ',

u'cai middle junsheng ',

u'cai m. junsheng ',

]for candidate in candidates:

print('candidate:', candidate)

match = address.search(candidate)

if match:

print(' match name :', match.groupdict()['first_name'],

end=' ')

print(match.groupdict()['last_name'])

print(' match email:', match.groupdict()['email'])

else:

print(' no match')

結果輸出如下:

candidate: cai junsheng

match name : cai junsheng

match email: [email protected]

candidate: different name

no match

candidate: cai middle junsheng

match name : cai junsheng

match email: [email protected]

candidate: cai m. junsheng

match name : cai junsheng

match email: [email protected]

在這個例子裡,就是通過(?p=first_name)引用。

python裡使用正規表示式的DOTALL標誌

正常的情況下,正規表示式裡的句號 是匹配任何除換行符之外的字元。但是有時你也想要求它連換行符也匹配,這時怎麼辦呢?其實不用急,可以使用dotall標誌,就可以讓它匹配所有字元,不再排除換行符了。如下例子 python 3.6 蔡軍生 import re text this is some text ...

python正規表示式及使用正規表示式的例子

正規表示式 正則表達用來匹配字串 正規表示式匹配過程 正規表示式語法規則 匹配除換行 n 外的任意字串 abcabc 轉義字元,使後乙個字元改變原來的意思 a c a c 字符集,對應的位置可以是字符集中任意字元,字符集中的字元可以逐個列出,也可以給出範圍,如 abc 或 a c 第乙個字元如果是 ...

python裡常用的正規表示式

1.使用者名稱import re 4到16位 字母,數字,下劃線,減號 if re.match r a za z0 9 abwc print 匹配 2.整數import re 正整數正則 if re.match r d 42 print 匹配 負整數正則 if re.match r d 42 pri...