python re模組的學習

2021-06-26 15:56:39 字數 1612 閱讀 8023

re模組是用來處理正規表示式的,正規表示式幾乎在每一門語言中都有,用處可謂很大,主要用與搜尋、匹配和替代,向郵箱、手機號碼的匹配,搜尋對應的檔名並進行替換等,下邊稍微羅列一下python常用的re模組中的相關函式,基本符號的使用這裡就不說了

re.match從字串的開頭查詢匹配的字元

re.search從字串的任意位置查詢匹配字元

import re

test = "click the button!"

matchstr = re.match("the",test)

if matchstr is none:

print "matchstr is none"

searchstr = re.search("the",test)

if searchstr is not none:

print searchstr.group()

結果顯示:

re.sub(arg1,arg2,arg3) 說明:arg3中的arg1被arg2替換

import re

text = "i love c++"

# 文字替換 (string.replace 速度更快)

print re.sub("c\+\+", "python", text)

#將空白字元轉換為[tab]

print re.sub("\s+", "[tab]", text)

# 將所有單詞替換為 word

print re.sub("\s+", "word", text)

結果顯示:

將正規表示式編譯為乙個物件,這樣執行起來更快

import re

import string

text = "i love c++"

temp = re.compile("c\+\+")

print temp.sub("python",text)

結果顯示:

查詢所有匹配的字串,返回結果為乙個列表

import re

import string

text = "[email protected] [email protected] [email protected] [email protected] [email protected]"

temp = re.compile("[a-z]+@\d.com")

結果顯示:

用正規表示式切割字串

import re

import string

text = "12:29:56"

temp = re.compile(":")

print temp.split(text)

print temp.findall(text)

結果顯示:

Python re模組學習

這是re模組與正則的結合 re模組提供的函式 1.match 嘗試在字串的開頭應用該模式,返回匹配物件,如果沒有找到匹配,則為none。1 importre2 3 str1 why are you keeping this curiosity door locked?4 res re.match w...

python re模組學習(1)

1 表示匹配最後乙個字元,有多少就返回多少 例 import re result re.match r abc abcccc result.group abcccc 如例 re裡最後的字元c有多少個,就匹配多少個,如果乙個都沒有,就只返回之前的字元 2 表示匹配最後乙個字元,至少要有1個,有多少返回...

Python re 正則模組

有些字元比較特殊,它們和自身並不匹配,而是會表明應和一些特殊的東西匹配,或者它們會影響到 re 其它部分的重複次數,它們叫元字元。其中 m 和 n 是十進位制整數。該限定符的意思是至少有 m 個重複,至多到 n 個重複。舉個例子,a b 將匹配 a b a b 和 a b 它不能匹配 ab 因為沒有...