如果给定字符串与给定模式匹配则返回true的算法

时间:2022-06-20 01:53:59

Anyone has an idea of how to implement an algorithm finding if string match a specific pattern?( not contains it!) without the use of regular expression...

任何人都知道如何在不使用正则表达式的情况下实现算法查找字符串是否匹配特定模式?(不包含它!)...

Rules are,the pattern can hold sign like ? or *:
? = one character or number
* = multiple characters or number or non at all

规则是,模式可以举行标志吗?要么 *: ? =一个字符或数字* =多个字符或数字或根本不存在

For example:

isMatching("??Ab", "cbAb") return true.
isMatching("*a?Ab", "123cacAbAAb") return false.
isMatching("*a?Ab", "123aaAb") return true.
isMatching("*a?Ab", "007aaabAb") return true.

isMatching(“?? Ab”,“cbAb”)返回true。 isMatching(“* a?Ab”,“123cacAbAAb”)返回false。 isMatching(“* a?Ab”,“123aaAb”)返回true。 isMatching(“* a?Ab”,“007aaabAb”)返回true。

isMatching("a?D*", "arD1324687e") return true.

isMatching(“a?D *”,“arD1324687e”)返回true。

1 个解决方案

#1


Some type of recursion would be simple enough:

某种类型的递归很简单:

def match(pattern, str):
    return match_(pattern, str)

def match_(pattern, str)
   if len(pattern) == 0 and len(str) == 0:
       return True

   switch pattern[0]:
       case '?':
            match_(pattern[1: ], str[1: ])
       case '*':
            return match_(pattern, str[1: ]) or match_(pattern[1: ], str[1: ]) or match_(pattern[1: ], str)
       default:
            return pattern[0] == str[0] and match_(pattern[1: ], str[1: ])

#1


Some type of recursion would be simple enough:

某种类型的递归很简单:

def match(pattern, str):
    return match_(pattern, str)

def match_(pattern, str)
   if len(pattern) == 0 and len(str) == 0:
       return True

   switch pattern[0]:
       case '?':
            match_(pattern[1: ], str[1: ])
       case '*':
            return match_(pattern, str[1: ]) or match_(pattern[1: ], str[1: ]) or match_(pattern[1: ], str)
       default:
            return pattern[0] == str[0] and match_(pattern[1: ], str[1: ])