Python re 模块的 Split, Sub, Subn 函数

2024年8月29日 | 23 分钟阅读

在深入了解 Python re 模块的 Split、Sub、Subn 函数之前,让我们先稍微了解一下 Python 提供的 re 模块。

正则表达式(RE)是一个特殊的文本字符串,在定义计算机语言中的搜索模式时非常有用。它非常适合从文本中提取数据,例如代码、文件、日志、电子表格,甚至论文。正则表达式(也称为 RE、regexes 或 regex patterns)是一个小型、高度专业化的计算机语言,它集成在 Python 中,并可以通过 re 模块访问。您使用这种小型语言来提供要匹配的潜在字符串集合的标准;这个集合可能包括英语短语、电子邮件地址、TeX 指令或您想要的任何其他内容。然后您可以询问诸如“这个字符串是否匹配该模式?”或“这个字符串的任何地方是否都匹配该模式?”之类的问题。RE 也可以用于以多种方式修改或分割字符串。正则表达式模式会被转换为字节码,然后由 C 语言编写的匹配引擎执行。为了创建运行速度更快的字节码,可能需要密切关注引擎将如何执行特定的 RE,并在高级使用中以特定的样式编写 RE。

由于正则表达式语言简短且有限,因此无法使用正则表达式完成所有字符串处理任务。有些任务可以使用正则表达式完成,但表达式会非常复杂。在某些情况下,创建 Python 代码来执行处理可能更好;虽然 Python 代码比复杂的正则表达式慢,但它也可能更易于理解。

大多数字母和字符会直接匹配。例如,正则表达式 test 将完美匹配字符串 test。(可以启用不区分大小写的模式,允许此 RE 也匹配 Test 或 TEST;稍后将详细介绍。)此规则有一些例外;某些字符是特殊的元字符,不会匹配。相反,它们表示应匹配某些不寻常的内容,或者它们会通过重复或修改其含义来影响 RE 的其他部分。方括号 [ 和 ] 是我们将首先看到的字符串。它们用于标识字符类,即一组要匹配的字符。可以指定单个字符,或者使用两个字符和 '-' 来分隔它们来指定字符范围。[abc] 例如,将匹配字母 a、b 或 c 中的任何一个;这与 [a-c] 相同,后者使用范围表示相同的字符集。如果您只想匹配小写字母,您的 RE 将是 [a-z]。在字符类内部,元字符是无效的。

通过对集合取反,您可以匹配不包含在类中的字符。“ ^ ”作为类的初始字符表示这一点。例如,[^5] 将匹配除字母 '5' 之外的任何字符。如果 caret 出现在字符类的其他任何位置,它就没有特殊含义。[5] 例如,将匹配 '5' 或 '^'。

反斜杠可能是最重要的元字符。反斜杠后面可以跟不同的字符,表示不同的特定序列,就像 Python 字符串字面量一样。

可以使用反斜杠来转义正则表达式中的所有特殊字符,它在定义正则表达式中的各种字符方面起着非常重要的作用。

特殊字符和常规字符都可以在正则表达式中使用。最简单的正则表达式是常规字符,例如 'A'、'a' 或 '0';它们直接匹配自身。常规字符可以连接,因此 last 匹配字符串 'last'。有些字符,例如 '|' 和 '(',是特殊的。特殊字符要么表示常规字符的类,要么影响周围正则表达式的解释。

重复限定符(*、+、?、{m,n} 等)不能直接嵌套。这消除了与非贪婪后缀 ? 以及其他实现中的其他修饰符的歧义。括号可用于为内部重复添加第二个重复。例如,(?:a6*) 匹配任何重复六次的字母 'a'。

上面讨论的那些字符是

  • . (点)。在默认模式下,它匹配除换行符外的任何字符。如果设置了 DOTALL 标志,它将匹配任何字符,包括换行符。
  • $ 匹配字符串的结尾或字符串结尾的换行符之前,以及 MULTILINE 模式中换行符之前。正则表达式 foo$ 仅匹配 'foo',而 foo 匹配 'foo' 和 'foobar'。
  • ^ (脱字符)。匹配字符串的开头,以及 MULTILINE 模式中每个换行符之后。
  • + 结果 RE 必须匹配前一个 RE 的一个或多个重复。ab+ 将匹配 'a' 之后任意数量的非零个 'b';它不会仅匹配 'a'。
  • * 使结果 RE 匹配前一个 RE 的 0 次或多次重复,最多可重复多次。ab* 将匹配 'a' 之后任意数量的 'b'、'ab' 或 'a'。
  • {m} 指定前一个 RE 的精确 m 个副本必须匹配;如果匹配次数较少,则整个 RE 将匹配失败。例如,a6 将精确匹配六个 'a' 字符,而不是五个。
  • ? 使结果 RE 匹配前一个 RE 的 0 次或 1 次重复。ab? 将匹配 'a' 或 'ab'。
  • {m,n} 使结果 RE 匹配前一个 RE 的 m 到 n 次重复,并尽可能多地匹配。例如,a3,5 将匹配 3 到 5 个 'a' 字母。省略 m 时,下限设为零,省略 n 时,上限设为无穷大。例如,a4,b 将匹配 'aaaab' 或一千个 'a' 字母后跟一个 'b',但不匹配 'aaab'。如果省略逗号,则修饰符将被误认为是前面描述的形式。
  • {m,n}? 使结果 RE 匹配前一个 RE 的 m 到 n 次重复,尽可能少地匹配。此限定符是前一个的非贪婪对应项。例如,在 6 个字符的字符串 'aaaaaa' 中,a3,5 将匹配 5 个 'a' 字符,而 a3,5? 只会匹配 3 个字符。
  • | A|B 创建一个匹配 A 或 B 的正则表达式,其中 A 和 B 是任意 RE。'|' 可用于分隔任意数量的 RE。它也可以在组中使用(见下文)。当扫描目标字符串时,由 '|' 分隔的 RE 按从左到右的顺序进行尝试。当一个模式完全匹配时,允许一个分支。这意味着一旦 A 匹配,B 就不会再次测试,即使它会导致更长的整体匹配。换句话说,'|' 运算符永远不会贪婪。使用 | 或将其包含在字符类中(例如 [|])以匹配字面量 '|'。
  • (...) 组的内容可以在匹配完成后恢复,并可以使用下面的特殊序列数字在字符串的后续部分进行匹配。使用 \( 或 \) 来匹配字面量 ( 或 ),或将它们包装在字符类中:[(], [)]。
  • (?...) 这是一个扩展表示法(否则,'(' 后的 '?' 无意义)。'?' 后的第一个字符决定了构造的含义和进一步的语法。唯一的例外是 (?Pname>...),它默认不创建新组。当前支持的扩展如下所示。
  • (?:...) 非捕获形式的常规括号。匹配组的子字符串无法在模式中稍后检索或引用,因为它匹配括号内的任何正则表达式。
  • (?<=...) 如果...的匹配在当前位置之前结束,则匹配。这被称为肯定后行断言。由于后行会回溯三个字符并验证包含的模式是否匹配,因此 (?=abc)def 将在 'abcdef' 中找到匹配。包含的模式只能匹配固定长度的字符串,因此 abc 或 a|b 是可接受的,但 a* 和 a3,4 是不可接受的。

现在让我们看看 re 模块所有函数的相应代码。

Python re 模块中的 split() 方法

内置的 re 模块有一个 split() 方法,它根据正则表达式匹配来分割文本。

split() 函数具有以下语法

语法

这是语法

  • pattern 是一个具有匹配项的正则表达式,它将用作分隔符。
  • string 是将被分割的输入字符串。
  • maxsplit 确定最大分割次数。如果 maxsplit 为一,结果列表通常会包含两个元素。如果 maxsplit 为二,结果列表将包含三个元素,依此类推。
  • flags 参数是可选的,默认值为零。可以将一个或多个 regex 标志传递给 flags 参数。flags 选项会修改 regex 引擎在匹配模式时的行为。

Python re 模块中 split() 方法的代码如下:

代码

输出

nirnay@superbook:~$ python3 re1.py 
Select among the options printed below::
1. To use split() method of re module.
2. To use split() method of re module with maxsplit parameter.
3. To use split() method of re module with maxsplit and flag parameter.
4. To finish the code execution and exit.
1
Enter the string that you want to split.
Hi my name is nirnay khajuria and I'm author of this python code
Enter the regular expression for performing the split operation on the input string.
\s+
The result after the split operation::
['Hi', 'my', 'name', 'is', 'nirnay', 'khajuria', 'and', "I'm", 'author', 'of', 'this', 'python', 'code']
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use split() method of re module.
2. To use split() method of re module with maxsplit parameter.
3. To use split() method of re module with maxsplit and flag parameter.
4. To finish the code execution and exit.
2
Enter the string that you want to split.
This example will show the use case of maxsplit parameter of the split() method of re module.
Enter the regular expression for performing the split operation on the input string.
\s+
Enter the maximum number of splits that you want.
6
The result after the split operation with maxsplit parameter::
['This', 'example', 'will', 'show', 'the', 'use', 'case of maxsplit parameter of the split() method of re module.']
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use split() method of re module.
2. To use split() method of re module with maxsplit parameter.
3. To use split() method of re module with maxsplit and flag parameter.
4. To finish the code execution and exit.
2
Enter the string that you want to split.
This example will show the use case of maxsplit parameter of the split() method of re module.
Enter the regular expression for performing the split operation on the input string.
\s+
Enter the maximum number of splits that you want.
9
The result after the split operation with maxsplit parameter::
['This', 'example', 'will', 'show', 'the', 'use', 'case', 'of', 'maxsplit', 'parameter of the split() method of re module.']
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use split() method of re module.
2. To use split() method of re module with maxsplit parameter.
3. To use split() method of re module with maxsplit and flag parameter.
4. To finish the code execution and exit.
3
Enter the string that you want to split.
This example will show the use case of maxsplit parameter of the split() method of re module.
Enter the regular expression for performing the split operation on the input string.
\s+
Enter the maximum number of splits that you want.
20 
The result after the split operation with maxsplit and flag parameter::
['This', 'example', 'will', 'show', 'the', 'use', 'case', 'of', 'maxsplit', 'parameter', 'of', 'the', 'split()', 'method', 'of', 're', 'module.']
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use split() method of re module.
2. To use split() method of re module with maxsplit parameter.
3. To use split() method of re module with maxsplit and flag parameter.
4. To finish the code execution and exit.
4

说明

因此,在上面的代码中,我们看到了 split 方法的用法以及如何使用不同的参数来使用此方法。在上面的代码中,我们创建了一个类,其中包含不同的函数,代表 split 函数的各种用例场景及其不同参数。第一个函数用于显示 split 方法及其默认输入参数的用法,有两个默认输入参数,即输入字符串和正则表达式,这两个输入参数用于根据指定的正则表达式分割输入字符串。第二个函数表示 split 方法与 max split 参数的用法,在这种情况下,根据用户指定的 max split 参数限制了基于提供的正则表达式的输入字符串的分割。在最后一个函数中,我们使用了 split 函数的 flag 参数。

Python re 模块中的 sub() 函数

返回通过用字符串中模式的最左边非重叠实例的替换 repl 替换而获得的字符串。如果找不到模式,则字符串保持不变。换句话说,n 变成单个换行符,r 变成回车符,依此类推。未知的 ASCII 字母转义保留供将来使用,并被视为错误。其他未识别的转义,如 &,则自行处理。

语法

  • 要匹配的正则表达式称为模式。除了正则表达式之外,模式还可以是 Pattern 对象。
  • count 参数表示 sub() 方法应替换的最大匹配数。
  • repl 是替换字符串。如果 count 参数设置为 0 或完全省略,sub() 函数将替换所有匹配项。
  • flags 是一个或多个 regex 标志,它们会改变模式的默认行为。

sub() 函数在字符串中搜索模式,并用替换字符串 (repl) 替换匹配的字符串。如果 sub() 函数未能找到匹配项,则返回原始字符串。否则,sub() 函数会替换匹配项并返回字符串。sub() 函数会替换模式的最左边非重叠的重复项。在下面的示例中,您将看到更详细的说明。

代码

输出

nirnay@superbook:~$ python3 re2.py 
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
1
Enter the string on which you want to perform the replacement.
This-is-a-simple-string-having-hyphen-instead-of-space
Enter the regular expression according to which you want to do replace on the input string.
\-
The result after the sub-operation::
This is a simple string having a hyphen instead of a space
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
2
Enter the string on which you want to perform the replacement.
This-is-a-simple-string-having-hyphen-instead-of-space
Enter the regular expression according to which you want to do replace on the input string.
\-
Enter repl string.
_
The result after the sub-operation::
This_is_a_simple_string_having_hyphen_instead_of_space
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
3
Enter the string on which you want to perform the replacement.
This-is-a-simple-string-having-hyphen-instead-of-space
Enter the regular expression according to which you want to do replace on the input string.
\-
Enter repl string.
_
Enter max count.
5
The result after the sub-operation::
This_is_a_simple_string_having-hyphen-instead-of-space
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
1
Enter the string on which you want to perform the replacement.
Only replace the hyphen in this-sentence
Enter the regular expression according to which you want to do replace on the input string.
\-
The result after the sub-operation::
Only replace the hyphen in this sentence
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
2
Enter the string on which you want to perform the replacement.
Replace +this string+
Enter the regular expression according to which you want to do replace on the input string.
\+
Enter repl string.
*
The result after the sub-operation::
Replace *this string*

Move further with code execution enter (y/n) as the input
Y
Select among the options printed below::
1. To use sub() method of re module.
2. To use sub() method of re module with repl parameter.
3. To use sub() method of re module with repl and count parameters.
4. To finish the code execution and exit.
3
Enter the string on which you want to perform the replacement.
My m@il is [email protected]
Enter the regular expression according to which you want to replace on the input string.
\@
Enter repl string.
a
Enter max count.
1
The result after the sub-operation::
My mail is [email protected]
Move further with code execution enter (y/n) as the input
N

说明

对于上面编写的代码,我们看到了 sub 方法的用法及其与不同参数的用法。在上面编写的代码中,我们创建了一个类,其中包含不同的函数,代表 sub 函数的各种用例场景及其不同参数。第一个函数用于显示 sub 方法及其默认输入参数的用法,有两个默认输入参数,即输入字符串和正则表达式,这两个输入参数用于根据指定的正则表达式替换输入字符串。第二个函数表示 sub 方法与 repl 参数的用法,在这种情况下,基于提供的正则表达式的输入字符串的替换受 count 参数的限制,如最后一个函数所示。

re 模块中的 subn 函数

Python 中的正则表达式 (RE) 模块有一个名为 subn() 的函数,该函数定义了字符串或一组字符串或与之匹配的模式。在使用此函数之前,必须导入 RE 模块。subn() 方法与 sub() 函数类似,但它还提供了您已执行的替换次数的计数。

语法

  • 第一个参数 pattern 指定要替换的文本或模式。
  • 第二个选项 repl 指定将用于替换模式的字符串/模式。
  • 第三个选项 string 指定将用于 subn() 函数的字符串。
  • 第四个选项 count 指定在执行 subn() 操作之前应进行多少次替换。
  • 第五个参数 flags 有助于代码缩减,并执行与 split 操作类似的角色。

代码

输出

Select among the options printed below::
1. To use subn() method of re module.
2. To use subn() method of re module with repl parameter.
3. To use subn() method of re module with repl and count parameters.
4. To finish the code execution and exit.
1
Enter the string on which you want to perform the replacement.
This is a sample string to show the usage of subn() function.
Enter the regular expression according to which you want to do replace on the input string.
()
The result after the subm operation::
('This is a sample string to show the usage of subn function.', 1)
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use subn() method of re module.
2. To use subn() method of re module with repl parameter.
3. To use subn() method of re module with repl and count parameters.
4. To finish the code execution and exit.
2
Enter the string on which you want to perform the replacement.
The repl p@r@meter is used to repl@ce with a specific string
Enter the regular expression according to which you want to do replace on the input string.
\@
Enter repl string.
a
The result after the subn operation::
('The repl parameter is used to replace with a specific string', 3)
Move further with code execution enter (y/n) as the input
y
Select among the options printed below::
1. To use subn() method of re module.
2. To use subn() method of re module with repl parameter.
3. To use subn() method of re module with repl and count parameters.
4. To finish the code execution and exit.
3
Enter the string on which you want to perform the replacement.
My m@il is [email protected]
Enter the regular expression according to which you want to do replace on the input string.
\@
Enter repl string.
a
Enter max count.
1
The result after the subn operation::
('My mail is [email protected]', 1)
Move further with code execution enter (y/n) as the input	
y
Select among the options printed below::
1. To use subn() method of re module.
2. To use subn() method of re module with repl parameter.
3. To use subn() method of re module with repl and count parameters.
4. To finish the code execution and exit.
4

说明

对于上面编写的代码,我们看到了 subn 方法的用法以及它与不同参数的用法。在上面编写的代码中,我们创建了一个类,其中包含不同的函数,代表 subn 函数的各种用例场景及其不同参数。第一个函数用于显示 subn 方法及其默认输入参数的用法,有两个默认输入参数,即输入字符串和正则表达式,这两个输入参数用于根据指定的正则表达式替换输入字符串。第二个函数表示 subn 方法与 repl 参数的用法,在这种情况下,基于提供的正则表达式的输入字符串的替换受 count 参数的限制,如最后一个函数所示。

结论

因此,在本篇文章中,我们理解了 Python re 模块的 Split、Sub、Subn 函数的用法。我们还看到了使用这些函数在不同场景下的示例 Python 代码。