我有以下正则表达式/代码段:
import js_regex
# I got 2 regexes
a = js_regex.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]$")
b = js_regex.compile(r"^\$[A-Z]{3}$")
# which I can test like this:
if a.match("BE46138E7195"):
print("match a")
if b.match("$USD"):
print("match b")
if not a.match("BDDD"):
print("not matching works")
# ab: third pattern to combine a and b
# first question: is this possible without making a new js_regex?
ab = js_regex.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]||$[A-Z]{3}$")
if ab.match("BE46138E7195"):
print("match ab")
if ab.match("$USD"):
print("match ab")
if not ab.match("BDDD"):
print("not matching works")
如您所见,有两个正则表达式,并且已经有了第一个问题(请参见代码片段)。 但主要问题是。假设我有一个字符串列表:
["BED", "KLO", "BN"]
我想检查该列表中的所有字符串是否与我的ab
正则表达式匹配。
但是:如果它们都不匹配也可以,例如:
["A", "B", "C"]
可以,因为它们都不匹配。所以我有两个可能的小组: [AB]和[not AB]
解决这个问题的最好方法是什么
您的
ab
模式是错误的,您的||
内部允许空字符串匹配,您只需要一个|
即可定义替换接下来,如果没有正确地对模式进行分组,则需要用
^(?:p1|p2)$
包装p1|p2
所以,如果您想声明
ab
模式,您将使用您可以这样使用此模式:
请参见Python演示:
输出:
根据每个字符串检查(AB检查),我会这样做:
现在,如果要检查整个列表是否匹配:
它是如何工作的:
all
-仅当迭代器中的所有值都具有布尔值True
时返回True
因此,在检查字符串是否不匹配的情况下,必须首先还原每个
alist
列表元素的结果如果可以合并两个正则表达式,请单独提问。基本上,您可以:对于正则表达式A或B,您可以构造正则表达式A | B。通常,(A)|(B)以确保替代方案位于整个正则表达式之间,而不是它们的一部分
相关问题 更多 >
编程相关推荐