Python教程-Python 正则表达式 - RegEx 函数 | 元字符 | 特殊序列

正则表达式是一组具有高度特殊语法的字符,我们可以使用它们来查找或匹配其他字符或字符组。简而言之,正则表达式(或称为 Regex)在 UNIX 世界中被广泛使用。
导入 re 模块
# Importing re module
import re
Python 中的 re 模块对 Perl 风格的正则表达式提供全面支持。当实现或使用正则表达式时,如果发生错误,re 模块会引发 re.error 异常。
我们将介绍处理正则表达式的关键函数。
首先,一个小问题:在正则表达式中,许多字母在使用时具有特殊的含义,称为元字符。
大多数符号和字符会很容易匹配。 (可以启用不区分大小写的功能,使此正则表达式与 Python 或 PYTHON 匹配。)例如,正则表达式 'check' 将仅匹配字符串 'check'。
这个一般规则也有一些例外,某些符号是特殊的元字符,不会匹配字符。相反,它们表示它们必须比较一些不寻常的内容,或者通过重复或修改它们的含义来影响正则表达式的其他部分。
元字符或特殊字符
顾名思义,有一些具有特殊含义的字符:
字符 | 含义 |
---|---|
. | 点号 - 匹配除换行符外的任意字符。 |
^ | 插入符号 - 用于从字符串开头匹配模式。 (以...开始) |
$ | 美元符号 - 匹配换行符之前的字符串末尾。 (以...结束) |
* | 星号 - 匹配模式的零个或多个出现。 |
+ | 加号 - 当我们想要模式至少匹配一次时使用。 |
? | 问号 - 匹配模式的零次或一次出现。 |
{} | 大括号 - 匹配模式的指定次数出现。 |
[] | 方括号 - 定义字符集。 |
** | 管道 - 匹配两个定义的模式之一。 |
特殊序列:
匹配不同字符集将是正则表达式首次实现的功能,以前无法通过字符串技术实现。另一方面,如果这是正则表达式的唯一附加功能,那么它的改进就不会太大。我们还可以定义正则表达式的某些部分必须重复出现指定的次数。
我们将首先讨论用于重复出现的第一个元字符:。与匹配实际字符 '' 不同,* 表示前一个字符可以出现 0 次或多次,而不仅仅是一次。
例如,Ba*t 将匹配 'bt'(零个 'a' 字符)、'bat'(一个 'a' 字符)、'baaat'(三个 'a' 字符)等。
贪婪重复,如 *,使匹配算法尝试尽可能多次地复制正则表达式。如果序列的后续元素无法匹配,则匹配算法将尝试较少次数的重复。
特殊序列由 '' 后面跟着下面的字符组成。每个字符都有不同的含义。
字符 | 含义 |
---|---|
d | 匹配任何数字,等效于 [0-9]。 |
D | 匹配任何非数字字符,等效于 1。 |
s | 匹配任何空白字符,等效于 [tnrfv]。 |
S | 匹配任何非空白字符,等效于 2。 |
w | 匹配任何字母数字字符,等效于 [a-zA-Z0-9]。 |
W | 匹配任何非字母数字字符,等效于 3。 |
A | 匹配字符串开头的定义模式。 |
b | r"bxt" - 匹配字符串中单词开头的模式。r"xtb" - 匹配字符串中单词末尾的模式。 |
B | 与 b 相反。 |
Z | 在模式位于字符串末尾时返回匹配对象。 |
RegEx 函数:
- compile - 用于将正则模式转换为可在字符串中匹配模式的正则表达式对象。
- search - 用于在给定字符串中查找正则模式的第一个匹配项。
- match - 从字符串开头开始匹配模式。
- fullmatch - 用于将整个字符串与正则模式匹配。
- split - 用于基于正则模式拆分字符串。
- findall - 用于在字符串中查找所有非重叠的模式。返回匹配模式的列表。
- finditer - 返回一个生成匹配对象的迭代器。
- sub - 替换字符串中第一个匹配模式后返回字符串。
- subn - 与 'sub' 相同。返回一个元组(新字符串,替换的次数)。
- escape - 用于在模式中转义特殊字符。
- purge - 用于清除正则表达式表达式缓存。
1. re.compile(pattern, flags=0)
它用于创建一个正则表达式对象,可用于在字符串中匹配模式。
示例:
# Importing re module
import re
# Defining regEx pattern
pattern = "amazing"
# Createing a regEx object
regex_object = re.compile(pattern)
# String
text = "This tutorial is amazing!"
# Searching for the pattern in the string
match_object = regex_object.search(text)
# Output
print("Match Object:", match_object)
输出:
Match Object:
2. re.match(pattern, string, flags=0)
- 它从字符串开头开始匹配模式。
- 如果找到匹配项,则返回匹配对象,其中包含有关其起始、结束、跨度等的信息。
- 如果未找到匹配项,则返回 None。
参数
- pattern:要匹配的表达式。必须是正则表达式。
- string:要在其开头与模式进行比较的字符串。
- flags:可以使用位运算 OR(|)来表示多个标志。
示例:
# Importing re module
import re
# Our pattern
pattern = "hello"
# Returns a match object if found else Null
match = re.match(pattern, "hello world")
print(match) # Printing the match object
print("Span:", match.span()) # Return the tuple (start, end)
print("Start:", match.start()) # Return the starting index
print("End:", match.end()) # Returns the ending index
输出:
Span: (0, 5)
Start: 0
End: 5
re.match() 方法的另一个示例。
- 表达式 ".w" 和 ".w?" 将匹配具有字母 "w" 的单词,而不具有字母 "w" 的内容将被忽略。
- 在此 Python re.match() 示例中,使用 for 循环检查列表中的每个元素的匹配。
代码:
import re
line = "Learn Python through tutorials on javatiku"
match_object = re.match( r'.w* (.w?) (.w*?)', line, re.M|re.I)
if match_object:
print ("match object group : ", match_object.group())
print ("match object 1 group : ", match_object.group(1))
print ("match object 2 group : ", match_object.group(2))
else:
print ( "There isn't any match!!" )
输出:
There isn't any match!!
3. re.search(pattern, string, flags=0)
re.search() 函数会查找正则表达式序列的第一个出现,并返回它。与 Python 的 re.match() 不同,它会验证所提供字符串的所有行。如果找到模式,则 re.search() 函数会产生一个匹配对象;否则,它返回 "null"。
要执行 search() 函数,我们首先必须导入 Python re 模块,然后运行程序。将“sequence”和“content”传递给 Python re.search() 调用,以便从主字符串中检查。
下面是参数的描述 -
pattern:要匹配的表达式。必须是正则表达式。
string:所提供的字符串是要在其中搜索模式的字符串。
flags:可以使用位运算 OR(|)来表示多个标志。这些是修改,下表列出了它们。
代码:
import re
line = "Learn Python through tutorials on javatiku";
search_object = re.search( r' .*t? (.*t?) (.*t?)', line)
if search_object:
print("search object group : ", search_object.group())
print("search object group 1 : ", search_object.group(1))
print("search object group 2 : ", search_object.group(2))
else:
print("Nothing found!!")
输出:
search object group : Python through tutorials on javatiku
search object group 1 : on
search object group 2 : javatiku
4. re.sub(pattern, repl, string, count=0, flags=0)
- 它将匹配模式在字符串中替换为 'repl'。
- 模式 - 仅是要匹配的正则模式。
- repl - repl 代表 "replacement",用于在字符串中替换模式。
- Count - 此参数用于控制替换的次数。
示例 1:
# Importing re module
import re
# Defining parameters
pattern = "like" # to be replaced
repl = "love" # Replacement
text = "I like javatiku!" # String
# Returns a new string with a substituted pattern
new_text = re.sub(pattern, repl, text)
# Output
print("Original text:", text)
print("Substituted text: ", new_text)
输出:
Original text: I like javatiku!
Substituted text: I love javatiku!
在上面的示例中,sub 函数将 'like' 替换为 'love'。
示例 2 - 替换模式的前三次出现。
# Importing re package
import re
# Defining parameters
pattern = "l" # to be replaced
repl = "L" # Replacement
text = "I like javatiku! I also like tutorials!" # String
# Returns a new string with the substituted pattern
new_text = re.sub(pattern, repl, text, 3)
# Output
print("Original text:", text)
print("Substituted text:", new_text)
输出:
Original text: I like javatiku! I also like tutorials!
Substituted text: I Like javatiku! I aLso Like tutorials!
在上面的程序中,subn 函数在字符串中的前三次出现 'l' 处将其替换为 "L"。
5. re.subn(pattern, repl, string, count=0, flags=0)
- subn 的工作方式与 sub 函数相同
- 它返回一个元组(新字符串,替换的次数)
示例:
# Importing re module
import re
# Defining parameters
pattern = "l" # to be replaced
repl = "L" # Replacement
text = "I like javatiku! I also like tutorials!" # String
# Returns a new string with the substituted pattern
new_text = re.subn(pattern, repl, text, 3)
# Output
print("Original text:", text)
print("Substituted text:", new_text)
输出:
Original text: I like javatiku! I also like tutorials!
Substituted text: ('I Like javatiku! I aLso Like tutorials!', 3)
在上面的程序中,subn 函数在字符串中的前三次出现 'l' 处将其替换为 "L"。
6. re.fullmatch(pattern, string, flags=0)
- 它将整个字符串与模式进行匹配。
- 返回相应的匹配对象。
- 如果未找到匹配项,则返回 None。
- 另一方面,search() 函数只会在字符串中搜索匹配模式的第一个出现。
示例:
# Importing re module
import re
# Sample string
line = "Hello world";
# Using re.fullmatch()
print(re.fullmatch("Hello", line))
print(re.fullmatch("Hello world", line))
输出:
None
在上面的程序中,只有 'Hello world" 完全匹配了模式,而 'Hello' 并没有。
Q. 何时使用 re.findall()?
答:假设我们有一行文本,想要从内容中获取所有出现的内容,因此我们使用 Python 的 re.findall() 函数。它会在提供给它的内容中搜索所有匹配项。
7. re.finditer(pattern, string, flags=0)
- 返回一个迭代器,该迭代器产生字符串中模式的所有非重叠匹配项。
- 从左到右扫描字符串。
- 按照发现顺序返回匹配项。
# Importing re module
import re
# Sample string
line = "Hello world. I am Here!";
# Regex pattern
pattern = r'[aeiou]'
# Using re.finditer()
iter_ = re.finditer(pattern, line)
# Iterating the itre_
for i in iter_:
print(i)
输出:
8. re.split(pattern, string, maxsplit=0, flags=0)
- 它将模式按模式出现的位置进行分割。
- 如果 maxsplit 为零,则进行最大数量的分割。
- 如果 maxsplit 为 1,则它将通过模式的第一个出现进行分割,并将剩余字符串作为最终结果返回。
示例:
# Import re module
import re
# Pattern
pattern = ' '
# Sample string
line = "Learn Python through tutorials on javatiku"
# Using split function to split the string after ' '
result = re.split( pattern, line)
# Printing the result
print("When maxsplit = 0, result:", result)
# When Maxsplit is one
result = re.split(pattern, line, maxsplit=1)
print("When maxsplit = 1, result =", result)
输出:
When maxsplit = 0, result: ['Learn', 'Python', 'through', 'tutorials', 'on', 'javatiku']
When maxsplit = 1, result = ['Learn', 'Python through tutorials on javatiku']
9. re.escape(pattern)
- 它会在模式中转义特殊字符。
- 当字符串中包含正则表达式元字符时,escape 函数变得更加重要。
示例:
# Import re module
import re
# Pattern
pattern = 'https://cn.javatiku/'
# Using escape function to escape metacharacters
result = re.escape( pattern)
# Printing the result
print("Result:", result)
输出:
Result: https://www\.javatiku\.cn/
10. re.purge()
- 清除正则表达式对象的缓存。
示例:
# Importing re module
import re
# Define some regular expressions
pattern1 = r'\d+'
pattern2 = r'[a-z]+'
# Use the regular expressions
print(re.search(pattern1, '123abc'))
print(re.search(pattern2, '123abc'))
# Clear the regular expression cache
re.purge()
# Use the regular expressions again
print(re.search(pattern1, '456def'))
print(re.search(pattern2, '456def'))
输出:
匹配与搜索-re.match (重新搜索()
Python有两个主要的正则表达式函数: match和search。match函数只在字符串开始的地方查找匹配项,而search函数在字符串的所有地方查找匹配项。
代码:
# Import re module
import re
# Sample string
line = "Learn Python through tutorials on javatiku"
# Using match function to match 'through'
match_object = re.match( r'through', line, re.M|re.I)
if match_object:
print("match object group : ", match_object)
else:
print( "There isn't any match!!")
# using search function to search
search_object = re.search( r'through', line, re.M|re.I)
if search_object:
print("Search object group : ", search_object)
else:
print("Nothing found!!")
输出:
There isn't any match!!
Search object group :
匹配函数检查字符串是否以“through”开头,搜索函数检查字符串中是否有“through”。