使用Python正則表達式操作文本數據

  • 來源 | 願碼(ChainDesk.CN)內容編輯
  • 願碼Slogan | 連接每個程序員的故事
  • 網站 | http://chaindesk.cn
  • 願碼願景 | 打造全學科IT系統免費課程,助力小白用戶、初級工程師0成本免費系統學習、低成本進階,幫助BAT一線資深工程師成長並利用自身優勢創造睡後收入。
  • 官方公衆號 | 願碼 | 願碼服務號 | 區塊鏈部落
  • 免費加入願碼全思維工程師社羣 | 任一公衆號回覆“願碼”兩個字獲取入羣二維碼

本文閱讀時長:7min

什麼是正則表達式


正則表達式,是簡單地字符的序列,可指定特定的搜索模式。正則表達式已存在很長一段時間,並且它本身就是計算機科學的一個領域。

在 Python中,使用Python的內置re模塊處理正則表達式操作 。在本節中,我將介紹創建正則表達式並使用它們的基礎知識。您可以使用以下步驟實現正則表達式:

  1. 指定模式字符串

  2. 將模式字符串編譯爲正則表達式對象。

  3. 使用正則表達式對象在字符串中搜索模式。

  4. 可選:從字符串中提取匹配的模式。

編寫和使用正則表達式


在Python中創建正則表達式的第一步是導入re 模塊:

import re

Python正則表達式使用模式字符串表示,模式字符串是指定所需搜索模式的字符串。在最簡單的形式中,模式字符串只能由字母,數字和空格組成。以下模式字符串表示精確字符序列的搜索查詢。您可以將每個角色視爲一個單獨的模式。在後面的例子中,我將討論更復雜的模式:

import re

pattern_string = "this is the pattern"

下一步是將模式字符串處理爲Python可以使用的對象,以便搜索模式。這是使用re模塊的compile()方法完成的。的編譯()方法將圖案字符串作爲參數並返回一個正則表達式對象:

import re

pattern_string = "this is the pattern" regex = re.compile(pattern_string)

獲得正則表達式對象後,可以使用它在搜索字符串搜索模式字符串中指定的模式。搜索字符串只是您要在其中查找模式的字符串的名稱。要搜索模式,可以使用regex對象的search()方法,如下所示:

import re

pattern_string = "this is the pattern" regex = re.compile(pattern_string)

match = regex.search("this is the pattern")

如果模式字符串中指定的模式位於搜索字符串中,則search()方法將返回匹配對象。否則,它返回None數據類型,這是一個空值。

由於Python相當鬆散地解釋了True和False值,因此搜索函數的結果可以像if語句中的布爾值一樣使用,這可能相當方便:

....

match = regex.search("this is the pattern") if match:

print("this was a match!")

這個模式應該產生一個匹配,因爲它與模式字符串中指定的模式完全匹配。如果在搜索字符串的任意位置找到模式,搜索函數將生成匹配,如下所示:

....

match = regex.search("this is the pattern") if match:

print("this was a match!")

if regex.search("*** this is the pattern ***"): print("this was not a match!")

if not regex.search("this is not the pattern"): print("this was not a match!")

特殊字符


正則表達式取決於使用某些特殊字符來表達模式。因此,除非用於預期目的,否則不應直接使用以下字符:

. ^ $ * + ? {} () [] | 

如果確實需要使用模式字符串中的任何前面提到的字符來搜索該字符,則可以編寫以反斜槓字符開頭的字符。這稱爲轉義字符。這是一個例子:

pattern string = "c*b"

## matches "c*b"

如果需要搜索反斜槓字符本身,則使用兩個反斜槓字符,如下所示:

pattern string = "cb"

## matches "cb"

匹配空格


在模式字符串中的任何位置使用s都匹配空白字符。這比空格字符更通用,因爲它適用於製表符和換行符:

....

a_space_b = re.compile("asb") if a_space_b.search("a b"):

print("'a b' is a match!")

if a_space_b.search("1234 a b 1234"): print("'1234 a b 1234' is a match")

if a_space_b.search("ab"):

print("'1234 a b 1234' is a match")

匹配字符串的開頭


如果在模式字符串的開頭使用^字符,則只有在搜索字符串的開頭找到模式時,正則表達式纔會產生匹配:

....

a_at_start = re.compile("^a") if a_at_start.search("a"):

print("'a' is a match")

if a_at_start.search("a 1234"): print("'a 1234' is a match")

if a_at_start.search("1234 a"): print("'1234 a' is a match")

匹配字符串的結尾


類似地,如果在模式字符串的末尾使用$符號,則正則表達式將僅在模式出現在搜索字符串的末尾時生成匹配:

....

a_at_end = re.compile("a$") if a_at_end.search("a"):

print("'a' is a match") if a_at_end.search("a 1234"):

print("'a 1234' is a match") if a_at_end.search("1234 a"):

print("'1234 a' is a match")

匹配一系列字符


可以匹配一系列字符而不是一個字符。這可以爲模式增加一些靈活性:

[A-Z] matches all capital letters

[a-z] matches all lowercase letters

[0-9] matches all digits

....

lower_case_letter = re.compile("[a-z]") if lower_case_letter.search("a"):

print("'a' is a match")

if lower_case_letter.search("B"): print("'B' is a match")

if lower_case_letter.search("123 A B 2"): print("'123 A B 2' is a match")

digit = re.compile("[0-9]") if digit.search("1"):

print("'a' is a match") if digit.search("342"):

print("'a' is a match") if digit.search("asdf abcd"):

print("'a' is a match")

匹配幾種模式中的任何一種


如果存在構成匹配的固定數量的模式,則可以使用以下語法組合它們:

(||)

以下a_or_b正則表達式將匹配任何字符或ab字符的字符串:

....

a_or_b = re.compile("(a|b)") if a_or_b.search("a"):

print("'a' is a match") if a_or_b.search("b"):

print("'b' is a match") if a_or_b.search("c"):

print("'c' is a match")

匹配序列而不是僅匹配一個字符


如果+字符位於另一個字符或模式之後,則正則表達式將匹配該模式的任意長序列。這非常有用,因爲它可以很容易地表達可以是任意長度的單詞或數字。

將模式放在一起


通過一個接一個地組合圖案串可以產生更復雜的圖案。在下面的示例中,我創建了一個正則表達式,用於搜索嚴格後跟單詞的數字。生成正則表達式的模式字符串由以下內容組成:

與數字序列匹配的模式字符串:[0-9]+與空白字符匹配的模式字符串:s與字母序列匹配的模式字符串:[az] +

與字符串結尾或空格字符匹配的模式字符串:(s | $)

....

number_then_word = re.compile("[0-9]+s[a-z]+(s|$)")

正則表達式split()函數


Python中的Regex 對象也有一個split()方法。split方法將搜索字符串拆分爲子字符串數組。所述分裂發生在沿着其中該圖案被識別的字符串中的每個位置。結果是在模式的實例之間出現的字符串數組。如果模式出現在搜索字符串的開頭或結尾,則分別在結果數組的開頭或結尾包含一個空字符串:

....

print(a_or_b.split("123a456b789")) print(a_or_b.split("a1b"))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章