Wildcard Matching in Python


Suppose we have an input string s and another input string p. Here is the main string and p is the pattern. We have to define one method, that can match pattern in the string. So we have to implement this for a regular expression, that supports wildcard characters like ‘?’ And ‘*’.

  • Dot ‘?’ Matches any single character

  • Star ‘*’ Matches zero or more characters.

So for example, if the input is like s = “aa” and p = “a?”, then it will be true, for the same input string, if the patter is “?*”, then it will be true.

To solve this, we will follow these steps −

  • ss := size of s and ps := size of p

  • make dp a matrix of size ss x ps, and fill this using false value

  • Update p and s by adding one blank space before these

  • For i in range 1 to ps −

    • if p[i] = star, then

      • dp[0, i] := dp[0, i - 1]

  • for i in range 1 to ss

    • for j in range 1 to ps

      • if s[i] is p[j], or p[j] is ‘?’, then

        • dp[i, j] := dp[i – 1, j – 1]

      • otherwise when p[j] is star, then

        • dp[i, j] := max of dp[i – 1, j] and dp[i, j – 1]

  • return dp[ss, ps]

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def isMatch(self, s, p):
      sl = len(s)
      pl = len(p)
      dp = [[False for i in range(pl+1)] for j in range(sl+1)]
      s = " "+s
      p = " "+p
      dp[0][0]=True
      for i in range(1,pl+1):
         if p[i] == '*':
            dp[0][i] = dp[0][i-1]
      for i in range(1,sl+1):
         for j in range(1,pl+1):
            if s[i] == p[j] or p[j] == '?':
               dp[i][j] = dp[i-1][j-1]
            elif p[j]=='*':
               dp[i][j] = max(dp[i-1][j],dp[i][j-1])
      return dp[sl][pl]
ob = Solution()
print(ob.isMatch("aa", "a?"))
print(ob.isMatch("aaaaaa", "a*"))

Input

"aa", "a."
"aaaaaa", "a*"

Output

True
True

Updated on: 26-May-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements