如何检查多个正则表达式js_regex中的字符串列表是否都匹配相同的正则表达式

2024-09-29 19:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下正则表达式/代码段:

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]

解决这个问题的最好方法是什么


Tags: ifabmatchjsnotthisregexusd
2条回答

您的ab模式是错误的,您的||内部允许空字符串匹配,您只需要一个|即可定义替换

接下来,如果没有正确地对模式进行分组,则需要用^(?:p1|p2)$包装p1|p2

所以,如果您想声明ab模式,您将使用

ab = js_regex.compile(r"^(?:[A-Z]{2}[A-Z0-9]{9}[0-9]|\$[A-Z]{3})$")

您可以这样使用此模式:

def validate(arr):
    return (all(map(ab.search, arr)) or all(map(lambda x: not ab.search(x), arr)) )

请参见Python演示:

import js_regex, re
 
a = js_regex.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]$")
b = js_regex.compile(r"^\$[A-Z]{3}$")
ab = re.compile(f'{a.pattern}|{b.pattern}') # Build the ab pattern from the two above

def validate(arr):
    return (all(map(ab.search, arr)) or all(map(lambda x: not ab.search(x), arr)) )
 
l1 = ["BED", "KLO", "BN"]
l2 = ["A", "B", "C"]
l3 = ["xxx", "$AUD"]
l4 = ['XX46434G8630', '$USD', 'XX46434V7047']
print(validate(l1), validate(l2), validate(l3), validate(l4), sep="\n")

输出:

True
True
False
True

根据每个字符串检查(AB检查),我会这样做:

if a.match(txt) and b.match(txt):
   print("We have a match!")

现在,如果要检查整个列表是否匹配:

def ab_match(txt):
   return a.match(txt) and b.match(txt)


list_res = [ab_match(txt) for txt in alist]

all_match = all(list_res)

all_no_match = all((not res for res in list_res))

它是如何工作的:

all-仅当迭代器中的所有值都具有布尔值True时返回True

因此,在检查字符串是否不匹配的情况下,必须首先还原每个alist列表元素的结果

如果可以合并两个正则表达式,请单独提问。基本上,您可以:对于正则表达式A或B,您可以构造正则表达式A | B。通常,(A)|(B)以确保替代方案位于整个正则表达式之间,而不是它们的一部分

相关问题 更多 >

    热门问题