Python 中 正規表示式

2021-10-08 14:44:19 字數 3798 閱讀 5674

一、最近要對字串執行很多操作,所以學了正規表示式

不得不說正規表示式對字串的操作還是很給力的

runoob上面的教程:

python中的正規表示式

正規表示式教程

python中要使用正規表示式,首先要匯入re模組 import re

二、常用函式(或者說方法)

re.match()

作用:嘗試從字串的起始位置匹配乙個模式,如果匹配成功的話,就返回乙個物件,否則返回none。注意,這個函式只匹配字串開始的位置。

語法:re.match(pattern, string, flags=0)

import re

str =

'hello,world!'

s = re.

match

('h'

, str)

s1 = re.

match

('w'

, str)

print

(s, s1,

)print

(s.group()

)# 輸出

,1), match=

'h'>

none

h

如果要取出搜尋到的值 可以用物件.group()來獲取

示例:

import re

str =

'hello,world!'

s = re.

match

('h.*r'

, str)

print

(s)print

(s.group()

)# 輸出

,9), match=

'hello,wor'

>

hello,wor

這裡第一行輸出了找到的物件,第二行輸出了物件的值。

這個正規表示式的意思是,查詢乙個以 h開頭r結尾,中間有0個或者多個字元組成的字串

如果要取出找到的物件,在字串中的索引值,可以用物件.span()來獲取,這裡不演示了

re.search()

作用:掃瞄整個字串並返回第乙個成功的匹配。

re.search() 和 re.match() 函式很像,只不過這個是在整個字串中匹配

語法:re.search(pattern, string, flags=0)

re.findall()

語法:re.findall(pattern,string[, pos[, endpos]])

import re

str =

'hello,world!'

s = re.

findall

('l'

,str)

s1 = re.

findall

('.l'

,str)

print

(s)print

(s1)

print

(s1[1]

)# 輸出

['l'

,'l'

,'l'][

'hel'

,'orl'

]orl

re.findall() 返回的是符合條件的乙個列表,可以通過下標獲取列表裡的值。

re.finditer()

re.finditer() 和 re.findall(),使用方法一樣,不過這個返回的是乙個迭代器,可以通過迴圈把裡面的值取出來

示例:

import re

str =

'hello,world!'

s1 = re.

finditer

(r'.l'

,str)

print

(s1)

for i in s1:

print

(i.group()

)# 輸出

>

helorl

re.split()

作用:把字串按照指定的字元或者正規表示式分割,並返回分割後的列表,這個用處非常大

語法:re.split(pattern, string[, maxsplit=0, flags=0])

import re

str =

'hello,world!'

s1 = re.

split

('w'

,str)

s2 = re.

split

(','

,str)

print

(s1)

print

(s2)

# 輸出

['hello,'

,'orld!'][

'hello'

,'world!'

]

第乙個按照字母 『w』 進行分割。 第二個按照逗號 『,』 進行分割。

re.compile()

作用:編譯正規表示式,生成乙個正規表示式,或作建立乙個正規表示式

語法:re.compile(pattern[, flags])

示例:

s1 = re.

compile

('^h.*o'

)

正規表示式修飾符 - 可選標誌

前面哪些方法裡 flags=0 這個引數的值,常用的有 re.i ,表示在匹配的時候不區分大小寫。其他的模式請自行查閱教程。

正規表示式

這個也得自己去查閱教程了,去學。

這裡舉幾個例子:

import re

str =

['hello,=world!'

,'hello,*python'

,'are you ok?'

,'how =are you?'

]s1 = re.

compile

('^h'

) # 查詢以h開頭 的字串

# 把列表中符合條件的值列印出來

for i in str:

if re.

search

(s1,i)

:print

(i)# 輸出

hello,

=world!

hello,

*python

how =are you?

import re

str =

['hello,=world!'

,'hello,*python'

,'are you: ok?'

,'how are you?'

]s2 = re.

compile

('[=*:]'

) # 查詢包含 等號『=』 或者 星號『*『 或者冒號『:』 的字串

# 把列表中符合條件的值列印出來

for i in str:

if re.

search

(s2,i)

:print

(i)# 輸出

hello,

=world!

hello,

*python

are you: ok?

python中正規表示式

python中正規表示式語法與linux中的相容 檢視正規表示式 python提供re模組,包含所有正規表示式的功能。由於python的字串本身也用 轉義,所以要特別注意 s abc 001 python的字串 對應的正規表示式字串變成 abc 001 建議使用python的r字首,就不用考慮轉義的...

Python中正規表示式

python re模組正規表示式中常用的字元有兩類 普通字元和11個元字元,元字元表示特定的功能,比如下面的 被括起來的表示式將作為分組,從表示式左邊開始每遇到乙個分組的左括號 編號 1。分組表示式作為乙個整體,可以後接數量詞。表示式中的 僅在該組中有效。那麼我們想匹配表示式中的 字元怎麼辦呢?通過...

python中正規表示式使用

1 正規表示式的常用操作符 操作符說明例項 表示任何單個字元 字符集,對單個字元給出取值範圍 abc 表示a b c,a z 表示a到z單個字元 非字符集,對單個字元給出排除範圍 abc 表示非a或b或c的單個字元 前乙個字元0次或無限次擴充套件 abc 表示ab abc abcc abccc等 前...