Python中正則表達式的基本用法

正則表達式(regular expression)是一種用於描述字符串結構的語法規則,利用一些特殊符號和組合,可以方便地進行字符串的匹配、查找、替換等操作。在Python中,通過re模塊可以實現正則表達式的處理。

一、基本元字符

1、.:匹配任意單個字符,除了\n

示例代碼:

“`python
import re

pattern = r”hello.world”
string = “hello\nworld”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)
“`

輸出:No match

2、^:匹配字符串開頭

示例代碼:

“`python
import re

pattern = r”^hello”
string = “hello world”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)
“`

輸出:Match found: hello

3、$:匹配字符串結尾

示例代碼:

“`python
import re

pattern = r”world$”
string = “hello world”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)
“`

輸出:Match found: world

二、字符集

字符集用[]表示,匹配[]中的任意一個字符

示例代碼:

“`python
import re

pattern = r”[aeiou]”
string = “hello world”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)
“`

輸出:Match found: e

字符集中除了[a-z]等常見形式外,還可以使用如下縮寫:

  • \d:匹配任意一個數字
  • \D:匹配任意一個非數字字符
  • \s:匹配任意一個空白字符,包括空格、製表符、換行符等
  • \S:匹配任意一個非空白字符
  • \w:匹配任意一個字母、數字或下劃線
  • \W:匹配任意一個非字母、數字或下劃線的字符

示例代碼:

“`python
import re

pattern1 = r”\d”
pattern2 = r”\s”
pattern3 = r”\w”
string = “hello 123 world”

match1 = re.search(pattern1, string)

if match1:
print(“Match found: ” + match1.group())
else:
print(“No match”)

match2 = re.search(pattern2, string)

if match2:
print(“Match found: ” + match2.group())
else:
print(“No match”)

match3 = re.search(pattern3, string)

if match3:
print(“Match found: ” + match3.group())
else:
print(“No match”)
“`

輸出:

“`
Match found: 1
Match found:
Match found: h
“`

三、量詞

量詞可以控制匹配的次數,包括:

  • *:匹配前一個字符0或多次
  • +:匹配前一個字符1或多次
  • ?:匹配前一個字符0或1次
  • {n}:匹配前一個字符n次
  • {m,n}:匹配前一個字符至少m次,最多n次(不包括m或n)

示例代碼:

“`python
import re

pattern1 = r”o*l”
pattern2 = r”o+l”
pattern3 = r”o?l”
pattern4 = r”o{2}l”
pattern5 = r”o{1,2}l”
string1 = “hello world”
string2 = “hollo world”
string3 = “hllo world”
string4 = “hool world”
string5 = “hoool world”

match1 = re.search(pattern1, string1)

if match1:
print(“Match found: ” + match1.group())
else:
print(“No match”)

match2 = re.search(pattern2, string1)

if match2:
print(“Match found: ” + match2.group())
else:
print(“No match”)

match3 = re.search(pattern3, string1)

if match3:
print(“Match found: ” + match3.group())
else:
print(“No match”)

match4 = re.search(pattern4, string1)

if match4:
print(“Match found: ” + match4.group())
else:
print(“No match”)

match5 = re.search(pattern5, string1)

if match5:
print(“Match found: ” + match5.group())
else:
print(“No match”)

match6 = re.search(pattern5, string4)

if match6:
print(“Match found: ” + match6.group())
else:
print(“No match”)

match7 = re.search(pattern5, string5)

if match7:
print(“Match found: ” + match7.group())
else:
print(“No match”)
“`

輸出:

“`
Match found: ol
Match found: ol
Match found: l
No match
Match found: ol
Match found: ool
Match found: oool
“`

四、分組

分組通過()實現,可以將多個字符當成一個整體進行匹配。

示例代碼:

“`python
import re

pattern = r”(ab)+”
string1 = “ababab”
string2 = “ab”

match1 = re.search(pattern, string1)

if match1:
print(“Match found: ” + match1.group())
else:
print(“No match”)

match2 = re.search(pattern, string2)

if match2:
print(“Match found: ” + match2.group())
else:
print(“No match”)
“`

輸出:

“`
Match found: ababab
No match
“`

五、轉義字符

如果需要匹配正則表達式中的特殊字符本身,可以使用轉義字符\

示例代碼:

“`python
import re

pattern = r”\.”
string = “hello.world”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)
“`

輸出:

“`
Match found: .
“`

六、re模塊常用函數

在Python中,匹配正則表達式通常使用re模塊提供的函數實現。

  • re.search(pattern, string, flags=0):在string中搜索匹配pattern的第一個位置,返回MatchObject實例
  • re.match(pattern, string, flags=0):從string的起始位置開始搜索匹配pattern的第一個位置,返回MatchObject實例
  • re.findall(pattern, string, flags=0):搜索string中所有匹配pattern的子串,並返回一個由匹配字符串構成的列表
  • re.finditer(pattern, string, flags=0):搜索string中所有匹配pattern的子串,並返回一個由MatchObject實例構成的迭代器
  • re.split(pattern, string, maxsplit=0, flags=0):根據pattern進行分割字符串,返回分割後的列表
  • re.sub(pattern, repl, string, count=0, flags=0):使用repl替換string中匹配patter的子串,count控制替換次數

示例代碼:

“`python
import re

pattern = r”\d+”
string = “hello 123 world 456”

match = re.search(pattern, string)

if match:
print(“Match found: ” + match.group())
else:
print(“No match”)

match_all = re.findall(pattern, string)

if match_all:
print(match_all)

match_iter = re.finditer(pattern, string)

for match in match_iter:
print(match.group())

split_list = re.split(pattern, string)

print(split_list)

sub_str = re.sub(pattern, “X”, string)

print(sub_str)

sub_str_limit = re.sub(pattern, “X”, string, count=1)

print(sub_str_limit)
“`

輸出:

“`
Match found: 123
[‘123’, ‘456’]
123
456
[‘hello ‘, ‘ world ‘, ”]
hello X world X
hello X world 456
“`

七、flags參數

在使用re模塊時,可以使用flags參數指定不同的匹配選項,常用的選項包括:

  • re.I / re.IGNORECASE:忽略大小寫
  • re.S / re.DOTALL:匹配任意字符,包括換行符
  • re.M / re.MULTILINE:多行匹配
  • re.X / re.VERBOSE:忽略正則表達式中的空白符,以使表達式更易讀

示例代碼:

“`python
import re

pattern1 = r”(?i)hello”
pattern2 = r”(?s)hello.world”
pattern3 = r”(?m)^world$”
pattern4 = r”(?x)h e l l o . w o r l d”
string = “Hello\nWORLD\nhello.world”

match1 = re.search(pattern1, string)

if match1:
print(“Match found: ” + match1.group())
else:
print(“No match”)

match2 = re.search(pattern2, string)

if match2:
print(“Match found: ” + match2.group())
else:
print(“No match”)

match3 = re.search(pattern3, string)

if match3:
print(“Match found: ” + match3.group())
else:
print(“No match”)

match4 = re.search(pattern4, string)

if match4:
print(“Match found: ” + match4.group())
else:
print(“No match”)
“`

輸出:

“`
Match found: Hello
Match found: hello.world
Match found: WORLD
Match found: hello.world
“`

八、總結

正則表達式是一種強大的文本處理工具,掌握基本的語法規則可以使我們在處理字符串時更加靈活高效。在Python中,re模塊提供了方便的接口,能夠輕鬆實現正則表達式的匹配、查找、替換等操作。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/311308.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2025-01-05 13:23
下一篇 2025-01-05 13:23

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29

發表回復

登錄後才能評論