Python programming: wildcard pattern matching algorithm implementation and source code analysis

Python programming: wildcard pattern matching algorithm implementation and source code analysis

In actual software development, it is usually necessary to perform pattern matching on strings. One such case is with wildcard pattern matching. This article will introduce how to implement wildcard pattern matching in the Python language, and attach the complete source code.

Wildcard pattern matching refers to the use of wildcards when matching strings, which can represent any character or character set. There are different symbols for wildcards, such as ' ', '?', etc. Among them, ' 'can represent any character sequence of any length, and '?' can represent an arbitrary character.

Algorithm implementation idea:

  1. Traversing the original string S and matching string P
  2. Use two pointers to point to the starting positions of S and P respectively, and record the current traverse position (i, j) at the same time
  3. Assuming that the current character is '*', you can skip any length of the S string until the next character is matched, and then continue to traverse
  4. If S[i] and P[j] are equal or P[j] is '?', continue to traverse backwards
  5. If the third step does not match successfully, it will go back to the position of the last '*' and start matching from there again until it is completely matched or cannot be matched.

The following is the Python source code implementation:

def isMatch(S, P):
    i = j 

Guess you like

Origin blog.csdn.net/qq_33885122/article/details/132217675