我有一个关于正则表达式(在 python 中使用)的简单但棘手的问题,我在谷歌的任何地方都没有找到答案。是否有任何“技巧”如何按可选顺序制作两个捕获组?假设我们有以下内容:
.*abc.*
我想要的是也匹配这个:
.*acb.*
我知道我可以用
.*abc|acb.*
但问题是,如果我们有比 abc 更复杂的东西,代码会很长。没有任何解决方法可以说例如“以任意顺序匹配最后两个捕获组(或符号等)?
请您参考如下方法:
我真的不明白这个可以使正则表达式更短的任意顺序的东西是什么。另一方面,我可以向您展示如何使它具有可读性,即使您有很多选择。
import re
pattern = """
.* # match from starting the line
(?: # A non-capturing group starts so we can list lots of alternatives
abc| # alternative 1
acb # alternative 2
) # end of alternatives
.* # then match everything up to the end of the line
"""
re.search(pattern, 'qqabcqq', re.VERBOSE) # returns a match
re.search(pattern, 'qqacbqq', re.VERBOSE) # returns a match
re.search(pattern, 'qqaSDqq', re.VERBOSE) # does not return a match
那么我们刚刚在这里看到了什么?
"""... """ 结构是在 python 中定义多行字符串的便捷方式。
然后 re.VERBOSE 跳过空格和注释。作为the manual says :
Whitespace within the pattern is ignored, except when in a character class or when preceded by an unescaped backslash. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.
这两件事让您可以向正则表达式添加结构和注释。 Here是另一个很好的例子。
