詳解Python匹配多行文本塊的正則表達(dá)式
本文討論了在多行字符串中搜索特定模式的方法。 該解決方案折衷了已知和未知模式的幾種方法,并解釋了匹配模式的工作原理。
編寫(xiě)正則表達(dá)式以匹配多行字符串的原因
假設(shè)我們有以下文本塊:
Any compiled body of information is known as a data set. Depending on the situation's specifics, this may be a database or a simple array.\n \n IBM first used the term "data set," which meant essentially the same thing as "file," to describe a collection of related records.
從上面給出的文本塊中,需要找到起始文本,文本在下面幾行呈現(xiàn)。 重要的是要注意 \n 表示換行符而不是文字文本。
總而言之,我們想要跨多行查找和匹配文本,忽略文本之間可能出現(xiàn)的任何空行。 在上述文本的情況下,它應(yīng)該返回 Any compiled body… 行,并且 IBM 首先在單個(gè)正則表達(dá)式查詢(xún)中使用了 term… 行。
匹配多行字符串的可能解決方案
在討論這個(gè)特定問(wèn)題的解決方案之前,必須了解 regex(正則表達(dá)式)API 的不同方面,尤其是那些在整個(gè)解決方案中經(jīng)常使用的方面。
那么,讓我們從 re.compile() 開(kāi)始吧。
Python re.compile() 方法
re.compile() 將正則表達(dá)式模式編譯為正則表達(dá)式對(duì)象,我們可以使用該對(duì)象與 match()、search() 和其他描述的方法進(jìn)行匹配。
re.compile() 相對(duì)于未編譯模式的優(yōu)勢(shì)之一是可重用性。 我們可以多次使用已編譯的表達(dá)式,而不是為每個(gè)未編譯的模式聲明一個(gè)新字符串。
import re as regex
pattern = regex.compile(".+World")
print(pattern.match("Hello World!"))
print(pattern.search("Hello World!"))輸出:
<re.Match object; span=(0, 11), match='Hello World'>
<re.Match object; span=(0, 11), match='Hello World'>
Python re.search() 方法
re.search() 在字符串中搜索匹配項(xiàng),如果找到則返回一個(gè) Match 對(duì)象。
如果存在多個(gè)匹配項(xiàng),我們將返回第一個(gè)實(shí)例。
我們也可以不使用re.compile()直接使用,適用于只需要查詢(xún)一次的情況。
import re as regex
print(regex.search(".+World", "Hello World!"))輸出:
<re.Match object; span=(0, 11), match='Hello World'>
Python re.finditer() 方法
re.finditer() 匹配字符串中的模式并返回一個(gè)迭代器,該迭代器為所有非重疊匹配項(xiàng)提供 Match 對(duì)象。
然后我們可以使用迭代器迭代匹配項(xiàng)并執(zhí)行必要的操作; 匹配按照它們?cè)谧址袕淖蟮接业恼业椒绞脚判颉?/p>
import re as regex
matches = regex.finditer(r'[aeoui]', 'vowel letters')
for match in matches:
print(match)輸出:
<re.Match object; span=(1, 2), match='o'>
<re.Match object; span=(3, 4), match='e'>
<re.Match object; span=(7, 8), match='e'>
<re.Match object; span=(10, 11), match='e'>
Python re.findall() 方法
re.findall() 返回字符串中模式的所有非重疊匹配項(xiàng)的列表或元組。 從左到右掃描一個(gè)字符串。 并且匹配按照它們被發(fā)現(xiàn)的順序返回。
import re as regex # Find all capital words string= ',,21312414.ABCDEFGw#########' print(regex.findall(r'[A-Z]+', string))
輸出:
['ABCDEFG']
Python re.MULTILINE 方法
re.MULTILINE 的一個(gè)顯著優(yōu)勢(shì)是它允許 ^ 在每一行的開(kāi)頭而不是僅在字符串的開(kāi)頭搜索模式。
Python 正則表達(dá)式符號(hào)
當(dāng)以復(fù)雜的方式使用時(shí),正則表達(dá)式符號(hào)很快就會(huì)變得非常混亂。 以下是我們解決方案中使用的一些符號(hào),以幫助更好地理解這些符號(hào)的基本概念。
- ^ 斷言行首的位置
- 字符串匹配(區(qū)分大小寫(xiě)的)字符“字符串”
- . 匹配所有字符(用于行終止的符號(hào)除外)
- 盡可能頻繁地匹配先前給定的標(biāo)記。
- \n 匹配換行符
- \r 匹配一個(gè) (CR) 回車(chē)符
- ? 與前一個(gè)標(biāo)記匹配 0-1 次
- +? 盡可能少地匹配前一個(gè)標(biāo)記 1 到無(wú)限次。
- a-z 匹配 a 和 z 之間范圍內(nèi)的單個(gè)字符(區(qū)分大小寫(xiě))
使用 re.compile() 匹配 Python 中的多行文本塊
讓我們了解使用不同的模式。
示例代碼:
import re as regex multiline_string = "Regular\nExpression" print(regex.search(r'^Expression', multiline_string, regex.MULTILINE))
輸出:
<re.Match object; span=(8, 18), match='Expression'>
上面的表達(dá)式首先斷言它在行首的位置(由于 ^),然后搜索“表達(dá)式”的確切出現(xiàn)。
使用 MULTILINE 標(biāo)志確保檢查每一行是否出現(xiàn)“表達(dá)式”,而不僅僅是第一行。
示例代碼:
import re as regex
data = """Any compiled body of information is known as a data set. Depending on the situation's specifics, this may be a database or a simple array.\n
\n
IBM first used the term "data set," which meant essentially the same thing as "file," to describe a collection of related records.
"""
result = regex.compile(r"^(.+)(?:\n|\r\n)+((?:(?:\n|\r\n?).+)+)", regex.MULTILINE)
print(result.search(data)[0].replace("\n", ""))輸出:
Any compiled body of information is known as a data set. Depending on the situation's specifics, this may be a database or a simple array.IBM first used the term "data set," which meant essentially the same thing as "file," to describe a collection of related records.
正則表達(dá)式可以分解并簡(jiǎn)化為更小的塊以提高可讀性:
在第一個(gè)捕獲組 (.+) 中,每個(gè)字符都在行中匹配(除了與行終止符對(duì)應(yīng)的任何符號(hào)); 這個(gè)過(guò)程盡可能頻繁地進(jìn)行。
之后,在非捕獲組 (?:\n|\r\n) 中,盡可能多地匹配一個(gè)行結(jié)束符或者一個(gè)行結(jié)束符加回車(chē)。
至于第二個(gè)捕獲組 ((?:(?:\n|\r\n?).+)+,它由一個(gè)非捕獲組 (?:(?:\n|\r\n? ).+)+ 換行符或換行符加回車(chē)最多匹配一次。
每個(gè)字符都在非捕獲組之外匹配,不包括行終止符。 盡可能多地執(zhí)行此過(guò)程。
示例代碼:
import re as regex
data = """Regex In Python
Regex is a feature available in all programming languages used to find patterns in text or data.
"""
query=regex.compile(r"^(.+?)\n([\a-z]+)",regex.MULTILINE)
for match in query.finditer(data):
topic, content = match.groups()
print ("Topic:",topic)
print ("Content:",content)輸出:
Topic: Regex In Python
Content:
Regex is a feature available in all programming languages used to find patterns in text or data.
上面的表達(dá)式可以解釋如下:
在第一個(gè)捕獲組 (.+?) 中,盡可能少地匹配所有字符(除了行終止符,和以前一樣)。 之后,匹配單個(gè)換行符 \n。
匹配換行符后,在第二個(gè)捕獲組 (\n[a-z ]+) 中進(jìn)行如下操作。 首先,匹配換行符,然后盡可能多次匹配 a-z 之間的字符。
使用 re.findall() 在 Python 中匹配多行文本塊
示例代碼:
import re as regex
data = """When working with regular expressions, the sub() function of the re library is an invaluable tool.
the subroutine looks over the string for the given pattern and applies the given replacement to all instances where it is found.
"""
query = regex.findall('([^\n\r]+)[\n\r]([a-z \n\r]+)',data)
for results in query:
for result in results:
print(result.replace("\n",""))輸出:
When working with regular expressions, the sub() function of the re library is an invaluable tool.
the subroutine looks over the string for the given pattern and applies the given replacement to all instances where it is found
為了更好地理解正則表達(dá)式的解釋?zhuān)屛覀儼疵總€(gè)組對(duì)其進(jìn)行分解,看看每個(gè)部分的作用。
在第一個(gè)捕獲組 ([^\n\r]+) 中,盡可能多地匹配所有字符,不包括換行符或回車(chē)符。
之后,當(dāng)字符是表達(dá)式 [\n\r] 中的回車(chē)符或換行符時(shí)進(jìn)行匹配。
在第二個(gè)捕獲組 ([a-z \n\r]+) 中,a-z 或換行符或回車(chē)符之間的字符盡可能多地匹配。
到此這篇關(guān)于Python - 匹配多行文本塊的正則表達(dá)式的文章就介紹到這了,更多相關(guān)python正則表達(dá)式匹配多行內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
numpy的sum函數(shù)的axis和keepdim參數(shù)詳解
這篇文章主要介紹了numpy的sum函數(shù)的axis和keepdim參數(shù)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python面向?qū)ο笾?lèi)屬性和類(lèi)方法案例分析
這篇文章主要介紹了python面向?qū)ο笾?lèi)屬性和類(lèi)方法,結(jié)合案例形式分析了Python面相對(duì)象中類(lèi)屬性和類(lèi)方法的相關(guān)概念、原理與使用技巧,需要的朋友可以參考下2019-12-12
利用Python實(shí)現(xiàn)面部識(shí)別的方法詳解
人臉識(shí)別正在成為軟件開(kāi)發(fā)中的一種趨勢(shì)。它有助于識(shí)別人臉并使應(yīng)用程序更加健壯。本文將使用python和face_recognition庫(kù)創(chuàng)建一個(gè)簡(jiǎn)單的人臉識(shí)別,需要的可以參考一下2022-05-05
python調(diào)用百度通用翻譯API的方法實(shí)現(xiàn)
本文主要介紹了python調(diào)用百度通用翻譯API的方法實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
利用Python對(duì)文件夾下圖片數(shù)據(jù)進(jìn)行批量改名的代碼實(shí)例
今天小編就為大家分享一篇關(guān)于利用Python對(duì)文件夾下圖片數(shù)據(jù)進(jìn)行批量改名的代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-02-02

