正規表示式練習

2021-08-15 19:36:56 字數 1986 閱讀 2429

1、 匹配一段文字中的每行的郵箱

y='[email protected]@[email protected]@adfcom

'import

reret=re.findall('

\w+@(?:qq|163|126).com

',y)

print

(ret)

['

[email protected]

', '

[email protected]

', '

[email protected]

']

2、 匹配一段文字中的每行的時間字串,比如:『1990-07-12』;

time='

asfasf1990-07-12asdfaaabbbb434241

'import

reret=re.search(r'

(?p19[09]\d)-(?p\d+)-(?p\d+)

',time)

print(ret.group('

year'))

print(ret.group('

month'))

print(ret.group('

days

'))

1990

0712

#

3、 匹配一段文字中所有的身份證數字。

a='sfafsf,34234234234,1231313132,154785625475896587,sdefgr54184785ds85,4864465asf86845

'import

reret=re.findall('\d'

,a)print

(ret)

['

154785625475896587

']

#

q='3344,88888,7778957,10000,99999,414,4,867287672

'import

reret=re.findall('

[1-9][0-9]

',q)

print(ret)

['

88888

', '

7778957

', '

10000

', '

99999

', '

867287672

']

#

5、 匹配乙個浮點數

import

reret=re.findall('

-?\d+\.?\d*

','-1,-2.5,8.8,1,0')

print(ret)

['

-1', '

-2.5

', '

8.8', '

1', '

0']

#

6、 匹配漢字。 ^[\u4e00-\u9fa5]$

import

reret=re.findall('

[\u4e00-\u9fa5]

','的沙發史蒂芬')

print(ret)

['

的沙發史蒂芬

', '']

#

7、 匹配出所有整數

a='1,-3,a,-2.5,7.7,asdf

'import

reret=re.findall(r"

'(-?\d+)'

",str(re.split(','

,a)))

print(ret)

['

1', '

-3']

正規表示式練習

取出其中的參考文獻,注意到每行只有乙個參考文獻,所以直接用 re.search regex,line import re with open test2 r as f lines f.readlines regex re.compile r a z reg open refer.txt w for ...

正規表示式練習

字元描述 匹配前面的子表示式零次或多次。例如,zo 能匹配 z 以及 zoo 等價於。匹配前面的子表示式一次或多次。例如,zo 能匹配 zo 以及 zoo 但不能匹配 z 等價於 匹配前面的子表示式零次或一次。例如,do es 可以匹配 do does 中的 does doxy 中的 do 1 va...

正規表示式練習

一 身份證號碼匹配的正規表示式編寫 453555 1900 1201 0087 453555 1900 1201 008x 需要用到分組的概念 1 前6位,區域的編號 2 接下來的4位 出生年 3 接下來的4位 月日 4 最後四位 5 倒數第二位性別 最後一位為x 簡單的身份證的正規表示式 d 0 ...