Program to check regular expression pattern is matching with string or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s and a regular expression pattern. We have to check whether the given pattern matches with given string or not. In the regular expression, there are few rules −

  • . (period) which matches any single character

  • * (asterisk) which matches zero or more of the preceding element.

So, if the input is like pattern = "h.l*o" s = "hello", then the output will be True, as We have ra and then a single character

To solve this, we will follow these steps −

  • n := size of s

  • m := size of p

  • Define a function dp() . This will take i, j

  • if j is same as m, then

    • return i is same as n

  • match := true when (i < n and(s[i] is same as p[j] or p[j] is same as ".") otherwise false

  • if j + 1 & m and p[j + 1] is same as "*", then

    • return true when dp(i, j + 2) or (match and dp(i + 1, j)) otherwise false

  • return match and dp(i + 1, j + 1)

  • From the main method return dp(0, 0)

Example  

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, p, s):
      n = len(s)
      m = len(p)
      def dp(i, j):
         if j == m:
            return i == n
         match = i < n and (s[i] == p[j] or p[j] == ".")
         if j + 1 < m and p[j + 1] == "*":
            return dp(i, j + 2) or (match and dp(i + 1, j))
         return match and dp(i + 1, j + 1)
      return dp(0, 0)
ob = Solution()
pattern = "h.l*o"
s = "hello"
print(ob.solve(pattern, s))

Input

"h.l*o", "hello"

Output

True
raja
Published on 22-Dec-2020 08:40:01
Advertisements