Python正規表示式例項演練

2021-07-05 12:35:38 字數 2598 閱讀 7628

1、首先python中要使用regex,必須匯入模組 re

>>>import re

\的使用,要想輸出元字元(. * - + \ $ ^ 等),必須在前邊加\ , 才能輸出。

>>> string='this is a\nstring'

>>> print string

this is a

string

>>> string1=r'this is a\nstring'  #前邊加r可以當做乙個正則式,後邊全是字元,沒有其他含義

>>> print string1

this is a\nstring

2、下面我們看一下,re中常用的幾個函式:

re.match(regex,string)方法,只有當被搜尋字串的開頭匹配到定義的regex時,才能查詢到匹配物件。

>>> import re

>>> re.match(r'hello','hello world hello boys!')

<_sre.sre_match object at 0x7fcaa1b0c308>   #returnamatch_object

>>> re.match(r'world','hello world hello boys!')

>>>

re.search(regex,string)方法,這個不會只限制與在開頭進行匹配,而是在整個string中進行匹配,但是只返回匹配到的第乙個。

>>> match_obj = re.search(r'world','hello world ,hello world!') #returnamatch_object

>>> match_obj.group(0)

'world'

re.findall(regex,string)方法,這個是查詢所有的符合regex的element, 返回的時乙個list

>>> print re.findall(r'world','hello world ,hello world!')    

['world', 'world']

3、詳細講解一下前邊用到的group函式

>>> contactinfo = 'doe, john: 555-1212'

>>> match = re.search(r'(\w+), (\w+): (\s+)', contactinfo)

>>> match.group(0)

'doe, john: 555-1212'

>>> match.group(1)

'doe'

>>> match.group(2)

'john'

>>> match.group(3)

'555-1212'

>>> re.findall(r'(\w+), (\w+): (\s+)', contactinfo)

[('doe', 'john', '555-1212')]

>>> re.findall(r'\w+, \w+: \s+', contactinfo)

['doe, john: 555-1212']

可以看出findall()並不適用分組的形式。

4、下面看乙個匹配**號碼的例子

import re

#the regex of landline num and phone num

print "the landline regex: "

landline = '0538-1234567'

r_landline = r'\d-?\d'

matchobject_landline = re.match(r_landline,landline)

if matchobject_landline==none:

print "match fail"

else:

print "match success"

print "the phone num regex: "

phone_num = '+8618811112222'

r_phone_num = r'\+\d\d'

matchobject_phone = re.match(r_phone_num,phone_num)

if matchobject_phone==none:

print "match fail"

else:

print "match success"

5、再來看乙個匹配電子郵件的小例子:

import re

#before '@' is a str of length between 3 to 10 ,behind '@' is one more char ,the end is '.com' , '.cn' or .'.org'

email = r'\w@\w+(\.com|\.cn)'

match_object = re.match(email,'[email protected]') #return one match_object

print match_object.group(); #print the content of match_object

ok,thank you!

Python正規表示式例項

字元匹配 例項描述 python 匹配 python 字元類例項 描述 pp ython 匹配 python 或 python rub ye 匹配 ruby 或 rube aeiou 匹配中括號內的任意乙個字母 0 9 匹配任何數字。類似於 0123456789 a z 匹配任何小寫字母 a z 匹...

正規表示式例項

正規表示式例項 1.驗證數字 只能輸入1個數字 表示式 d 描述 匹配乙個數字 匹配的例子 0,1,2,3 不匹配的例子 2.只能輸入n個數字 表示式 d 例如 d 描述 匹配8個數字 匹配的例子 12345678,22223334,12344321 不匹配的例子 3.只能輸入至少n個數字 表示式 ...

正規表示式例項

正規表示式語法 字元匹配 正規表示式 china 匹配 chinaabc 句點符號 正規表示式 t.n 匹配 tan,tbn,tcn,t n,t n等 方括號符號 方括號只有裡面指定的字元才參與匹配,也就是說,正規表示式 t aeio n 只匹配 tan ten tin 和 ton 但 toon 不...