小码哥的IT人生

Python RegEx 正则表达式

Python基础 2022-06-06 12:54:18小码哥的IT人生shichen

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")

RegEx 函数

re 模块提供了一组函数,允许我们检索字符串以进行匹配:

函数 描述
findall 返回包含所有匹配项的列表
search 如果字符串中的任意位置存在匹配,则返回 Match 对象
split 返回在每次匹配时拆分字符串的列表
sub 用字符串替换一个或多个匹配项

元字符

元字符是具有特殊含义的字符:

字符 描述 示例 TIY
[] 一组字符 "[a-m]" 试一试
\ 示意特殊序列(也可用于转义特殊字符) "\d" 试一试
. 任何字符(换行符除外) "he..o" 试一试
^ 起始于 "^hello" 试一试
$ 结束于 "world$" 试一试
* 零次或多次出现 "aix*" 试一试
+ 一次或多次出现 "aix+" 试一试
{} 确切地指定的出现次数 "al{2}" 试一试
| 两者任一 "falls|stays" 试一试
() 捕获和分组    

特殊序列

特殊序列指的是 \ 后跟下表中的某个字符,拥有特殊含义:

字符 描述 示例 TIY
\A 如果指定的字符位于字符串的开头,则返回匹配项 "\AThe" 试一试
\b 返回指定字符位于单词的开头或末尾的匹配项 r"\bain"
r"ain\b"
试一试
试一试
\B 返回指定字符存在的匹配项,但不在单词的开头(或结尾处) r"\Bain"
r"ain\B"
试一试
试一试
\d 返回字符串包含数字的匹配项(数字 0-9) "\d" 试一试
\D 返回字符串不包含数字的匹配项 "\D" 试一试
\s 返回字符串包含空白字符的匹配项 "\s" 试一试
\S 返回字符串不包含空白字符的匹配项 "\S" 试一试
\w 返回一个匹配项,其中字符串包含任何单词字符
(从 a 到 Z 的字符,从 0 到 9 的数字和下划线 _ 字符)
"\w" 试一试
\W 返回一个匹配项,其中字符串不包含任何单词字符 "\W" 试一试
\Z 如果指定的字符位于字符串的末尾,则返回匹配项 "Spain\Z" 试一试

集合(Set)

集合(Set)是一对方括号 [] 内的一组字符,具有特殊含义:

集合 描述 试一试
[arn] 返回一个匹配项,其中存在指定字符(a,r 或 n)之一 试一试
[a-n] 返回字母顺序 a 和 n 之间的任意小写字符匹配项 试一试
[^arn] 返回除 a、r 和 n 之外的任意字符的匹配项 试一试
[0123] 返回存在任何指定数字(0、1、2 或 3)的匹配项 试一试
[0-9] 返回 0 与 9 之间任意数字的匹配 试一试
[0-5][0-9] 返回介于 0 到 9 之间的任何数字的匹配项 试一试
[a-zA-Z] 返回字母顺序 a 和 z 之间的任何字符的匹配,小写或大写 试一试
[+] 在集合中,+、*、.、|、()、$、{} 没有特殊含义,因此 [+] 表示:返回字符串中任何 + 字符的匹配项 试一试

findall() 函数

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

示例代码:

打印所有匹配的列表:

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

完整实例:

import re
#Return a list containing every occurrence of "ai":
str = "China is a great country"
x = re.findall("a", str)
print(x)

这个列表以被找到的顺序包含匹配项。

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

示例代码:

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

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

完整实例:

import re
str = "China is a great country"
#Check if "USA" is in the string:
x = re.findall("USA", str)
print(x)
if (x):
  print("Yes, there is at least one match!")
else:
  print("No match")

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())

完整实例:

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())

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

示例代码:

进行不返回匹配的检索:

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

完整实例:

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

split() 函数

split() 函数返回一个列表,其中字符串在每次匹配时被拆分:

示例代码:

在每个空白字符处进行拆分:

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

完整实例:

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

您可以通过指定 maxsplit 参数来控制出现次数:

示例代码:

仅在首次出现时拆分字符串:

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

完整实例:

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

sub() 函数

sub() 函数把匹配替换为您选择的文本:

示例代码:

用数字 9 替换每个空白字符:

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

完整实例:

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

您可以通过指定 count 参数来控制替换次数:

示例代码:

替换前两次出现:

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

完整实例:

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

Match 对象

Match 对象是包含有关搜索和结果信息的对象。

注释:如果没有匹配,则返回值 None,而不是 Match 对象。

示例代码:

执行会返回 Match 对象的搜索:

import re
str = "China is a great country"
x = re.search("a", str)
print(x) # 将打印一个对象

完整实例:

import re
str = "China is a great country"
x = re.search("a", str)
print(x) #this will print an object

Match 对象提供了用于取回有关搜索及结果信息的属性和方法:

  • span() 返回的元组包含了匹配的开始和结束位置
  • .string 返回传入函数的字符串
  • group() 返回匹配的字符串部分

示例代码:

打印首个匹配出现的位置(开始和结束位置)。

正则表达式查找以大写 "C" 开头的任何单词:

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

完整实例:

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

示例代码:

打印传入函数的字符串:

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

完整实例:

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

示例代码:

打印匹配的字符串部分。

正则表达式查找以大写 "C" 开头的任何单词:

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

完整实例:

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

注释:如果没有匹配项,则返回值 None,而不是 Match 对象。

完整实例1:

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)

完整实例2:

import re
str = "That will be 59 dollars"
#Find all digit characters:
x = re.findall("\d", str)
print(x)

完整实例3:

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)

完整实例4:

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")

完整实例5:

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")

完整实例6:

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")

完整实例7:

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")

完整实例8:

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")

完整实例9:

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")

完整实例10:

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")

完整实例11:

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")

完整实例12:

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")

完整实例13:

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")

完整实例14:

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")

完整实例15:

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")

完整实例16:

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")

完整实例17:

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")

完整实例18:

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")

完整实例19:

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")

完整实例20:

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")

完整实例21:

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")

完整实例22:

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")

完整实例23:

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")

完整实例24:

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")

完整实例25:

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")

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024