19- regular expression match

Title: Implement comprising a function for matching and '*' regular expression '.'. Mode character '.' Represents any one character '*' indicates that the preceding character can appear any number of times (including 0 time).

def re_match(string,pattern):

    if len(string) ==0 and len(pattern)==0:
        return True
    if len(string)!=0 and len(pattern)==0 or (len(string)==0 and len(pattern)!=0):
        return False

    if len(pattern)>1 and pattern[1] =='*':
        if pattern[0] == string[0] or (pattern[0]=='.' and len(string)!=0):

            return re_match(string[1:],pattern[2:]) or re_match(string[1:],pattern) or re_match(string,pattern[2:])
        else:
            return re_match(string,pattern[2:])

    if string[0]==pattern[0] or (pattern[0]=='.' and len(string)!=0):

        return re_match(string[1:],pattern[1:])

    return False

Note:

A recursive manner, the termination condition is: If the string pattern string and simultaneously reaches the end, it indicates matching, returns True; if you do not arrive simultaneously, False is returned.

'.' Mode, if the string is traversed, recursively traverse a string and the next bit string pattern; if traversing '*' to a slightly more complex, is determined to need '*' strings are the same whether the former, If not, skip pattern string '*', a next traversal, if the same, will have three cases recursion, '*' matches a time, multiple matching, match 0.

Guess you like

Origin www.cnblogs.com/kingshine007/p/11354117.html