循环列表以查找与带通配符的字符串的模式匹配

问题描述 投票:0回答:1

我有一个函数的示例代码,其中使用模式匹配将包含通配符的字符串值与实际字符串值进行匹配。

def isMatch(text, pattern):
    n = len(text)
    m = len(pattern)
    i = 0
    j = 0
    startIndex = -1
    match = 0

    while i < n:
        if j < m and (pattern[j] == '?' or pattern[j] == text[i]):
            i += 1
            j += 1
        elif j < m and pattern[j] == '*':
            startIndex = j
            match = i
            j += 1
        elif startIndex != -1:
            j = startIndex + 1
            match += 1
            i = match
        else:
            return False

    while j < m and pattern[j] == '*':
        j += 1

    return j == m


s = "RE340T6-1MCWW"
p = "RE340T*-*****"

if isMatch(s, p):
    print("Yes")
else:
    print("No")

在此示例代码中,字符串 (s)“RE340T6-1MCWW”与模式 (p)“RE340T*-*****”匹配,并返回“Yes”,这是理所应当的。

我想要做的是使用上面的函数,有一个字符串列表,并在带有通配符的字符串列表中查找匹配项。例如:

s = ['GUC 40 410','HUC 40 410','XUC 40 410'] p = ['GUC 40 4**','HUC 40 4**','XUC 40 4**']

我不知道如何在函数中的列表中插入循环以返回字符串 (s) 与模式 (p) 匹配的位置。对下一步有什么想法吗?

如果我只是用列表替换静态字符串,它只会返回“否”

python-3.x pandas dataframe pattern-matching wildcard
1个回答
0
投票

您可以简单地使用另一种

_find
方法来检查
isMatch()
:

def isMatch(text, pattern):
    n = len(text)
    m = len(pattern)
    i = 0
    j = 0
    startIndex = -1
    match = 0

    while i < n:
        if j < m and (pattern[j] == '?' or pattern[j] == text[i]):
            i += 1
            j += 1
        elif j < m and pattern[j] == '*':
            startIndex = j
            match = i
            j += 1
        elif startIndex != -1:
            j = startIndex + 1
            match += 1
            i = match
        else:
            return False

    while j < m and pattern[j] == '*':
        j += 1

    return j == m


def _find(S, ps):
    res = []
    for i, s in enumerate(S):
        for j, p in enumerate(ps):
            if isMatch(s, p):
                res.append((i, j))
    return res


s = ['GUC 40 410', 'HUC 40 410', 'XUC 40 410']
p = ['GUC 40 4**', 'HUC 40 4**', 'XUC 40 4**']

print(_find(s, p))

打印

[(0, 0), (1, 1), (2, 2)]
© www.soinside.com 2019 - 2024. All rights reserved.