目錄
RegEx 模組
Python 中的RegEx
# 字元:{} 描述: 確切指定的出現次數範例:「al{2}」
集合(Set)
findall() 函数
search() 函数
split() 函数
sub() 函数
Match 对象
首頁 後端開發 Python教學 Python的RegEx正規表示式怎麼使用

Python的RegEx正規表示式怎麼使用

May 19, 2023 pm 08:49 PM
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正規表示式怎麼使用

Python的RegEx正規表示式怎麼使用

Python的RegEx正規表示式怎麼使用

#RegEx 函數

re 模組提供了一組函數,允許我們檢索字串以進行匹配:Python的RegEx正規表示式怎麼使用

##元字元

元字元是具有特殊意義的字元

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)
登入後複製

執行範例

##字元:. 描述:任何字元(換行符除外) 範例: “he…o”Python的RegEx正規表示式怎麼使用

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)
登入後複製

執行範例

##字元:^ 說明:起始於範例: “^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")
登入後複製

執行範例

##字元:| 說明:兩者任一範例:「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」Python的RegEx正規表示式怎麼使用

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")
登入後複製

執行範例

字元:\bPython的RegEx正規表示式怎麼使用

描述:傳回指定字元位於單字的開頭或結尾的符合項目

範例: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")
登入後複製

運行範例

範例:r"ain\b"Python的RegEx正規表示式怎麼使用

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")
登入後複製

運行範例

##字元: \B

Python的RegEx正規表示式怎麼使用描述:傳回指定字元存在的符合項,但不在單字的開頭(或結尾)

範例: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")
登入後複製

執行範例

範例: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")
登入後複製
###執行範例## #############字元:\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正規表示式怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

模板化的優點和缺點有哪些? 模板化的優點和缺點有哪些? May 08, 2024 pm 03:51 PM

模板化的優點和缺點有哪些?

Google AI 為開發者發佈 Gemini 1.5 Pro 和 Gemma 2 Google AI 為開發者發佈 Gemini 1.5 Pro 和 Gemma 2 Jul 01, 2024 am 07:22 AM

Google AI 為開發者發佈 Gemini 1.5 Pro 和 Gemma 2

怎麼下載deepseek 小米 怎麼下載deepseek 小米 Feb 19, 2025 pm 05:27 PM

怎麼下載deepseek 小米

deepseek怎麼問他 deepseek怎麼問他 Feb 19, 2025 pm 04:42 PM

deepseek怎麼問他

evaluate函數怎麼保存 evaluate函數怎麼保存 May 07, 2024 am 01:09 AM

evaluate函數怎麼保存

NET40是什麼軟體 NET40是什麼軟體 May 10, 2024 am 01:12 AM

NET40是什麼軟體

deepseek該怎麼搜索 deepseek該怎麼搜索 Feb 19, 2025 pm 05:18 PM

deepseek該怎麼搜索

瀏覽器插件是什麼語言寫的 瀏覽器插件是什麼語言寫的 May 08, 2024 pm 09:36 PM

瀏覽器插件是什麼語言寫的

See all articles