正規表示式 匹配分組

2021-10-23 11:41:41 字數 2612 閱讀 1284

**功能|

匹配左右任意乙個表示式

(ab)

將括號中字元作為乙個分組

\num引用分組num匹配到的字串

(?p)分組起別名

(?p=name)

引用別名為name分組匹配到的字串

import re

# 水果列表

fruit_list =[,

"banana"

,"orange"

,"pear"

]# 遍歷資料

for value in fruit_list:

# | 匹配左右任意乙個表示式

match_obj = re.match(

, value)

if match_obj:

print

("%s是我想要的"

% match_obj.group())

else

:print

("%s不是我要的"

% value)

執行結果:

banana不是我要的

orange不是我要的

pear是我想要的

需求:匹配出163、126、qq等郵箱

import re

match_obj = re.match(

"[a-za-z0-9_]@(163|126|qq|sina|yahoo)\.com"

,"hello@163.com"

)if match_obj:

print

(match_obj.group())

# 獲取分組資料

print

(match_obj.group(1)

)else

:print

("匹配失敗"

)

執行結果:

hello@163.com

163

import re

match_obj = re.match(

"(qq):([1-9]\d)",)

if match_obj:

print

(match_obj.group())

# 分組:預設是1乙個分組,多個分組從左到右依次加1

print

(match_obj.group(1)

)# 提取第二個分組資料

print

(match_obj.group(2)

)else

:print

("匹配失敗"

)

執行結果:

qq

10567

需求:匹配出hh

match_obj = re.match(

"<[a-za-z1-6]+>.*"

,"hh")

if match_obj:

print

(match_obj.group())

else

:print

("匹配失敗"

)match_obj = re.match(

"<([a-za-z1-6]+)>.*"

,"hh"

)if match_obj:

print

(match_obj.group())

else

:print

("匹配失敗"

)

執行結果:

>

hhdiv

>

>

hhhtml

>

需求:匹配出www.baidu.cn

match_obj = re.match(

"<([a-za-z1-6]+)><([a-za-z1-6]+)>.*","

")if match_obj:

print

(match_obj.group())

else

:print

("匹配失敗"

)

執行結果:

>

>

www.itcast.cnh1

>

html

>

需求:匹配出www.itcast.cn

match_obj = re.match(

"<(?p[a-za-z1-6]+)><(?p[a-za-z1-6]+)>.*","

")if match_obj:

print

(match_obj.group())

else

:print

("匹配失敗"

)

執行結果:

>

>

www.itcast.cnh1

>

html

>

正規表示式匹配分組操作示例

匹配分組 匹配左右任意乙個表示式 將括號中的字元作為乙個分組 num 引用分組num匹配到的字元 p 給分組起別名 p name 引用別名為name的分組匹配到的字元 re.match r 0 9a za z 163 126 qq com group re.match r 0 9a za z 163...

正規表示式 基礎 python 5匹配分組

字元功能 匹配左右任意乙個表示式 ab 將括號中字元作為乙個分組 num 引用分組num匹配到的字串 p 分組起別名 p name 引用別名為name分組匹配到的字串 示例1 需求 匹配出0 100之間的數字 coding utf 8 import re ret re.match 1 9 d 8 p...

JavaScript 正規表示式的分組匹配

下面的正規表示式可以匹配kidkidkid kidkidkid 而另一種更優雅的寫法是 kid 這裡由圓括號包裹的乙個小整體稱為分組。乙個分組中,可以有多個候選表示式,用 分隔 var reg i love him her it reg.test i love him true reg.test i...