溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python的RegEx正則表達式怎么使用

發布時間:2023-04-27 11:48:48 來源:億速云 閱讀:128 作者:iii 欄目:開發技術

本文小編為大家詳細介紹“Python的RegEx正則表達式怎么使用”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Python的RegEx正則表達式怎么使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

RegEx 或正則表達式是形成搜索模式的字符序列。

RegEx 可用于檢查字符串是否包含指定的搜索模式。

RegEx 模塊

Python 提供名為 re 的內置包,可用于處理正則表達式。

導入 re 模塊:

import re

Python 中的 RegEx

導入 re 模塊后,就可以開始使用正則表達式了:

實例

檢索字符串以查看它是否以 “China” 開頭并以 “country” 結尾:

import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)

運行實例

import re

txt = "China is a great country"
x = re.search("^China.*country$", txt)

if (x):
  print("YES! We have a match!")
else:
  print("No match")

Python的RegEx正則表達式怎么使用

RegEx 函數

re 模塊提供了一組函數,允許我們檢索字符串以進行匹配:

Python的RegEx正則表達式怎么使用

元字符

元字符是具有特殊含義的字符

字符:[] 描述:一組字符 示例:“[a-m]”

import re

str = "The rain in Spain"

#Find all lower case characters alphabetically between "a" and "m":

x = re.findall("[a-m]", str)
print(x)

運行示例

Python的RegEx正則表達式怎么使用

字符: 描述:示意特殊序列(也可用于轉義特殊字符) 示例:“\d”

import re

str = "That will be 59 dollars"

#Find all digit characters:

x = re.findall("\d", str)
print(x)

運行示例

Python的RegEx正則表達式怎么使用

字符:. 描述:任何字符(換行符除外) 示例: “he…o”

import re

str = "hello world"

#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":

x = re.findall("he..o", str)
print(x)

運行示例

Python的RegEx正則表達式怎么使用

字符:^ 描述:起始于 示例: “^hello”

import re

str = "hello world"

#Check if the string starts with 'hello':

x = re.findall("^hello", str)
if (x):
  print("Yes, the string starts with 'hello'")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:$ 描述:結束于 示例:“world$”

import re

str = "hello world"

#Check if the string ends with 'world':

x = re.findall("world$", str)
if (x):
  print("Yes, the string ends with 'world'")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:* 描述:零次或多次出現 示例:“aix*”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains "ai" followed by 0 or more "x" characters:

x = re.findall("aix*", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:+ 描述:一次或多次出現 示例: “aix+”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains "ai" followed by 1 or more "x" characters:

x = re.findall("aix+", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:{} 描述: 確切地指定的出現次數 示例:“al{2}”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains "a" followed by exactly two "l" characters:

x = re.findall("al{2}", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:| 描述:兩者任一 示例:“falls|stays”

import re

str = "The rain in Spain falls mainly in the plain!"

#Check if the string contains either "falls" or "stays":

x = re.findall("falls|stays", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:() 描述:捕獲和分組

特殊序列

特殊序列指的是 \ 后跟下表中的某個字符,擁有特殊含義。

字符:\A 描述:如果指定的字符位于字符串的開頭,則返回匹配項 示例:“\AThe”

import re

str = "The rain in Spain"

#Check if the string starts with "The":

x = re.findall("\AThe", str)

print(x)

if (x):
  print("Yes, there is a match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\b

描述:返回指定字符位于單詞的開頭或末尾的匹配項

示例:r"\bain"

import re

str = "The rain in Spain"

#Check if "ain" is present at the beginning of a WORD:

x = re.findall(r"\bain", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

示例:r"ain\b"

import re

str = "The rain in Spain"

#Check if "ain" is present at the end of a WORD:

x = re.findall(r"ain\b", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\B

描述:返回指定字符存在的匹配項,但不在單詞的開頭(或結尾處)

示例:r"\Bain"

import re

str = "The rain in Spain"

#Check if "ain" is present, but NOT at the beginning of a word:

x = re.findall(r"\Bain", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

示例:r"ain\B"

import re

str = "The rain in Spain"

#Check if "ain" is present, but NOT at the end of a word:

x = re.findall(r"ain\B", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\d

描述:返回字符串包含數字的匹配項(數字 0-9)

示例:“\d”

import re

str = "The rain in Spain"

#Check if the string contains any digits (numbers from 0-9):

x = re.findall("\d", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\D

描述:返回字符串不包含數字的匹配項

示例:“\D”

import re

str = "The rain in Spain"

#Return a match at every no-digit character:

x = re.findall("\D", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\s

描述:返回字符串包含空白字符的匹配項

示例:“\s”

import re

str = "The rain in Spain"

#Return a match at every white-space character:

x = re.findall("\s", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\S

描述:返回字符串不包含空白字符的匹配項

示例:“\S”

import re

str = "The rain in Spain"

#Return a match at every NON white-space character:

x = re.findall("\S", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\w

描述: 返回一個匹配項,其中字符串包含任何單詞字符 (從 a 到 Z 的字符,從 0 到 9 的數字和下劃線 _ 字符)

示例:“\w”

import re

str = "The rain in Spain"

#Return a match at every word character (characters from a to Z, digits from 0-9, and the underscore _ character):

x = re.findall("\w", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\W

描述:返回一個匹配項,其中字符串不包含任何單詞字符

示例:“\W”

import re

str = "The rain in Spain"

#Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-space etc.):

x = re.findall("\W", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:\Z

描述:如果指定的字符位于字符串的末尾,則返回匹配項 。

示例:“Spain\Z”

import re

str = "The rain in Spain"

#Check if the string ends with "Spain":

x = re.findall("Spain\Z", str)

print(x)

if (x):
  print("Yes, there is a match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

集合(Set)

集合(Set)是一對方括號 [] 內的一組字符,具有特殊含義。

字符:[arn]

描述:返回一個匹配項,其中存在指定字符(a,r 或 n)之一

示例

import re

str = "The rain in Spain"

#Check if the string has any a, r, or n characters:

x = re.findall("[arn]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[a-n]

描述:返回字母順序 a 和 n 之間的任意小寫字符匹配項

示例

import re

str = "The rain in Spain"

#Check if the string has any characters between a and n:

x = re.findall("[a-n]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[^arn]

描述:返回除 a、r 和 n 之外的任意字符的匹配項

示例

import re

str = "The rain in Spain"

#Check if the string has other characters than a, r, or n:

x = re.findall("[^arn]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[0123]

描述:返回存在任何指定數字(0、1、2 或 3)的匹配項

示例

import re

str = "The rain in Spain"

#Check if the string has any 0, 1, 2, or 3 digits:

x = re.findall("[0123]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[0-9]

描述:返回 0 與 9 之間任意數字的匹配

示例

import re

str = "8 times before 11:45 AM"

#Check if the string has any digits:

x = re.findall("[0-9]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[0-5][0-9]

描述:返回介于 0 到 9 之間的任何數字的匹配項

示例

import re

str = "8 times before 11:45 AM"

#Check if the string has any two-digit numbers, from 00 to 59:

x = re.findall("[0-5][0-9]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[a-zA-Z]

描述:返回字母順序 a 和 z 之間的任何字符的匹配,小寫或大寫

示例

import re

str = "8 times before 11:45 AM"

#Check if the string has any characters from a to z lower case, and A to Z upper case:

x = re.findall("[a-zA-Z]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

字符:[+]

描述:在集合中,+、*、.、|、()、$、{} 沒有特殊含義,因此 [+] 表示:返回字符串中任何 + 字符的匹配項。

示例

import re

str = "8 times before 11:45 AM"

#Check if the string has any + characters:

x = re.findall("[+]", str)

print(x)

if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

運行示例

Python的RegEx正則表達式怎么使用

findall() 函數

findall() 函數返回包含所有匹配項的列表。

實例

打印所有匹配的列表

import re

str = "China is a great country"
x = re.findall("a", str)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

這個列表以被找到的順序包含匹配項。

如果未找到匹配項,則返回空列表。

實例

如果未找到匹配,則返回空列表:

import re

str = "China is a great country"
x = re.findall("USA", str)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

search() 函數

search() 函數搜索字符串中的匹配項,如果存在匹配則返回 Match 對象。

如果有多個匹配,則僅返回首個匹配項。

實例

在字符串中搜索第一個空白字符

import re

str = "China is a great country"
x = re.search("\s", str)

print("The first white-space character is located in position:", x.start())

運行實例

Python的RegEx正則表達式怎么使用

如果未找到匹配,則返回值 None:

實例

進行不返回匹配的檢索

import re

str = "China is a great country"
x = re.search("USA", str)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

split() 函數

split() 函數返回一個列表,其中字符串在每次匹配時被拆分。

實例

在每個空白字符處進行拆分

import re

str = "China is a great country"
x = re.split("\s", str)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

可以通過指定 maxsplit 參數來控制出現次數:

實例

僅在首次出現時拆分字符串:

import re

str = "China is a great country"
x = re.split("\s", str, 1)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

sub() 函數

sub() 函數把匹配替換為您選擇的文本

實例

用數字 9 替換每個空白字符

import re

str = "China is a great country"
x = re.sub("\s", "9", str)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

可以通過指定 count 參數來控制替換次數:

實例

替換前兩次出現

import re

str = "China is a great country"
x = re.sub("\s", "9", str, 2)
print(x)

運行實例

Python的RegEx正則表達式怎么使用

Match 對象

Match 對象是包含有關搜索和結果信息的對象。

注釋:如果沒有匹配,則返回值 None,而不是 Match 對象。

實例

執行會返回 Match 對象的搜索:

import re

str = "China is a great country"
x = re.search("a", str)
print(x) # 將打印一個對象

運行實例

Python的RegEx正則表達式怎么使用

Match 對象提供了用于取回有關搜索及結果信息的屬性和方法:

  • span() 返回的元組包含了匹配的開始和結束位置

  • .string 返回傳入函數的字符串

  • group() 返回匹配的字符串部分

實例

打印首個匹配出現的位置(開始和結束位置)。

正則表達式查找以大寫 “C” 開頭的任何單詞:

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.span())

運行實例

Python的RegEx正則表達式怎么使用

實例

打印傳入函數的字符串

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.string)

運行實例

Python的RegEx正則表達式怎么使用

實例

打印匹配的字符串部分

正則表達式查找以大寫 “C” 開頭的任何單詞:

import re

str = "China is a great country"
x = re.search(r"\bC\w+", str)
print(x.group())

運行實例

Python的RegEx正則表達式怎么使用

注釋:如果沒有匹配項,則返回值 None,而不是 Match 對象。

讀到這里,這篇“Python的RegEx正則表達式怎么使用”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女