
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check regular expression pattern is matching with string or not in Python
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 −
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
- Related Articles
- Lua pattern matching vs regular expression
- Regular Expression Matching in Python
- Program to check string is palindrome or not with equivalent pairs in Python
- Program to check string is palindrome with lowercase characters or not in Python
- Program to check the string is repeating string or not in Python
- Program to check a string is palindrome or not in Python
- Program to check given string is pangram or not in Python
- Regular Expression Matching in JavaScript
- Python program to check if a string is palindrome or not
- Python program to check if the string is empty or not
- What is the Python regular expression to check if a string is alphanumeric?
- Program to check string contains consecutively descending string or not in Python
- Which package is used for pattern matching with regular expressions in java?
- Pattern matching in Python with Regex
- Program to check given string is anagram of palindromic or not in Python
