正則表達式re.compile()的使用


re 模塊提供了不少有用的函數,用以匹配字符串,比如:

compile 函數
match 函數
search 函數
findall 函數
finditer 函數
split 函數
sub 函數
subn 函數
re 模塊的一般使用步驟如下:

使用 compile 函數將正則表達式的字符串形式編譯為一個 Pattern 對象
通過 Pattern 對象提供的一系列方法對文本進行匹配查找,獲得匹配結果(一個 Match 對象)
最后使用 Match 對象提供的屬性和方法獲得信息,根據需要進行其他的操作
compile 函數
compile 函數用於編譯正則表達式,生成一個 Pattern 對象,它的一般使用形式如下:

re.compile(pattern[, flag])
其中,pattern 是一個字符串形式的正則表達式,flag 是一個可選參數,表示匹配模式,比如忽略大小寫,多行模式等。

下面,讓我們看看例子。


import re
# 將正則表達式編譯成 Pattern 對象
pattern = re.compile(r'\d+')
在上面,我們已將一個正則表達式編譯成 Pattern 對象,接下來,我們就可以利用 pattern 的一系列方法對文本進行匹配查找了。Pattern 對象的一些常用方法主要有:

match 方法
search 方法
findall 方法
finditer 方法
split 方法
sub 方法
subn 方法

正則表達式re.compile()
compile()的定義:

compile(pattern, flags=0)
Compile a regular expression pattern, returning a pattern object.


從compile()函數的定義中,可以看出返回的是一個匹配對象,它單獨使用就沒有任何意義,需要和findall(), search(), match()搭配使用。
compile()與findall()一起使用,返回一個列表。

import re


def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
x = regex.findall(content)
print(x)


if __name__ == '__main__':
main()
# ['Hello', 'from', 'Chongqing', 'montain', 'to', 'you']

compile()與match()一起使用,可返回一個class、str、tuple。但是一定需要注意match(),從位置0開始匹配,匹配不到會返回None,返回None的時候就沒有span/group屬性了,並且與group使用,返回一個單詞‘Hello’后匹配就會結束。

import re


def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
y = regex.match(content)
print(y)
print(type(y))
print(y.group())
print(y.span())


if __name__ == '__main__':
main()
# <_sre.SRE_Match object; span=(0, 5), match='Hello'>
# <class '_sre.SRE_Match'>
# Hello
# (0, 5)

compile()與search()搭配使用, 返回的類型與match()差不多, 但是不同的是search(), 可以不從位置0開始匹配。但是匹配一個單詞之后,匹配和match()一樣,匹配就會結束。

import re


def main():
content = 'Hello, I am Jerry, from Chongqing, a montain city, nice to meet you……'
regex = re.compile('\w*o\w*')
z = regex.search(content)
print(z)
print(type(z))
print(z.group())
print(z.span())


if __name__ == '__main__':
main()
# <_sre.SRE_Match object; span=(0, 5), match='Hello'>
# <class '_sre.SRE_Match'>
# Hello
# (0, 5)

————————————————
版權聲明:本文為CSDN博主「艾莉寶貝」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_42793426/article/details/88545939


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM