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

Regular expression pattern matching is a common programming problem where we need to check if a string matches a given pattern. In Python, we can implement this using dynamic programming with recursive approach.

Regular Expression Rules

The pattern matching follows these rules ?

  • . (period) matches any single character

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

Algorithm Steps

To solve this problem, we follow these steps ?

  • Get the length of string s and pattern p

  • Create a recursive function dp(i, j) where i is the current position in string and j is the current position in pattern

  • If we reach the end of pattern, check if we also reached the end of string

  • Check if current characters match (considering . wildcard)

  • Handle the * quantifier which can match zero or more occurrences

Example

Let's implement the regular expression matching algorithm ?

class Solution:
    def solve(self, pattern, string):
        n = len(string)
        m = len(pattern)
        
        def dp(i, j):
            # Base case: reached end of pattern
            if j == m:
                return i == n
            
            # Check if current characters match
            match = i < n and (string[i] == pattern[j] or pattern[j] == ".")
            
            # Handle asterisk quantifier
            if j + 1 < m and pattern[j + 1] == "*":
                # Either skip the pattern (zero matches) or use it if current chars match
                return dp(i, j + 2) or (match and dp(i + 1, j))
            
            # Regular character matching
            return match and dp(i + 1, j + 1)
        
        return dp(0, 0)

# Test the solution
solution = Solution()
pattern = "h.l*o"
string = "hello"
result = solution.solve(pattern, string)
print(f"Pattern '{pattern}' matches '{string}': {result}")

The output of the above code is ?

Pattern 'h.l*o' matches 'hello': True

How It Works

Let's trace through the example "h.l*o" matching "hello" ?

  • h matches h ?

  • . matches e ? (dot matches any character)

  • l* matches ll ? (asterisk allows multiple l)

  • o matches o ?

Additional Examples

Here are more examples to understand the pattern matching ?

solution = Solution()

# Test cases
test_cases = [
    ("a*b", "aaaaab", True),      # Multiple 'a' followed by 'b'
    (".*", "anything", True),     # Dot-star matches everything
    ("c*a*b", "b", True),         # Zero 'c', zero 'a', one 'b'
    ("ab*c", "abc", True),        # One 'a', one 'b', one 'c'
    ("ab*c", "ac", True),         # One 'a', zero 'b', one 'c'
]

for pattern, string, expected in test_cases:
    result = solution.solve(pattern, string)
    status = "?" if result == expected else "?"
    print(f"{status} '{pattern}' vs '{string}' ? {result}")

The output shows various pattern matching scenarios ?

? 'a*b' vs 'aaaaab' ? True
? '.*' vs 'anything' ? True
? 'c*a*b' vs 'b' ? True
? 'ab*c' vs 'abc' ? True
? 'ab*c' vs 'ac' ? True

Time Complexity

The time complexity is O(m × n) where m is the pattern length and n is the string length. Space complexity is O(m × n) due to recursion stack depth.

Conclusion

Regular expression matching using dynamic programming provides an elegant solution for pattern matching problems. The key insight is handling the asterisk quantifier recursively by considering both zero matches and continuing with the current pattern.

Updated on: 2026-03-25T13:50:04+05:30

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements