Python之re模組詳解

2021-07-31 17:41:23 字數 2137 閱讀 2632

re.match 嘗試從字串的開始匹配乙個模式,如:下面的例子匹配第乙個單詞

import re

text = "jgood is a handsome boy, he is cool, clever, and so on..."

m = re.match(r"(\w+)\s", text)

if m:

print m.group(0), '\n', m.group(1)

else:

print

'not match'

re.match的函式原型為:re.match(pattern, string, flags)

第乙個引數是正規表示式,這裡為」(\w+)\s」,如果匹配成功,則返回乙個match,否則返回乙個none;

第二個引數表示要匹配的字串;

第三個引數是標緻位,用於控制正規表示式的匹配方式,如:是否區分大小寫,多行匹配等等。

re.search

re.search函式會在字串內查詢模式匹配,只到找到第乙個匹配然後返回,如果字串沒有匹配,則返回none。

import re

text = "jgood is a handsome boy, he is cool, clever, and so on..."

m = re.search(r'\shan(ds)ome\s', text)

if m:

print m.group(0), m.group(1)

else:

print

'not search'

re.search的函式原型為: re.search(pattern, string, flags)

每個引數的含意與re.match一樣

re.match與re.search的區別:re.match只匹配字串的開始,如果字串開始不符合正規表示式,則匹配失敗,函式返回none;而re.search匹配整個字串,直到找到乙個匹配。

re.sub

re.sub用於替換字串中的匹配項。下面乙個例子將字串中的空格 』 』 替換成 『-』 :

import re

text = "jgood is a handsome boy, he is cool, clever, and so on..."

print re.sub(r'\s+', '-', text)

re.sub的函式原型為:re.sub(pattern, repl, string, count)

其中第二個引數是替換後的字串;本例中為』-』

第四個引數指替換個數。預設為0,表示每個匹配項都替換

re.sub還允許使用函式對匹配項的替換進行複雜的處理。如:re.sub(r』\s』, lambda m: 『[』 + m.group(0) + 『]』, text, 0);將字串中的空格』 『替換為』[ ]』

re.split

可以使用re.split來分割字串,如:re.split(r』\s+』, text);將字串按空格分割成乙個單詞列表

re.findall

re.findall可以獲取字串中所有匹配的字串。如:re.findall(r』\w*oo\w*』, text);獲取字串中,包含』oo』的所有單詞

re.compile

可以把正規表示式編譯成乙個正規表示式物件。可以把那些經常使用的正規表示式編譯成正規表示式物件,這樣可以提高一定的效率。

import re

text = "jgood is a handsome boy, he is cool, clever, and so on..."

regex = re.compile(r'\w*oo\w*')

print regex.findall(text) #查詢所有包含'oo'的單詞

print regex.sub(lambda m: '[' + m.group(0) + ']', text) #將字串中含有'oo'的單詞用括起來

python模組 之 re模組

功能 實現python對正規表示式對支援與應用,將想要得到對內容按照正規表示式匹配出來 應用場景 爬蟲指令碼 對使用者輸入內容進行合規檢查 如qq格式檢查 等 功能 匹配物件中所有符合正規表示式的內容,並取出來 返回值 列表,所匹配到對項都會返回到列表中 import re content 1362...

re模組詳解

常用正規表示式符號12 3456 78910 1112 1314 1516 1718 1920 21 預設匹配除 n之外的任意乙個字元,若指定flag dotall,則匹配任意字元,包括換行 匹配字元開頭,若指定flags multiline,這種也可以匹配上 r a nabc neee flags...

python內建模組之re模組

在python要想使用正則必須借助於模組,re就是其中之一 查詢字串中所有匹配到的字元,並返回乙個列表,沒有匹配資料則返回乙個空列表 import re re.findall 正規表示式 帶匹配的文字 根據正則匹配除所有符合條件的資料 res re.findall b eva jason jacks...