- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Let us see the following implementation to get better understanding −
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=True for i in range(1,pl+1): if p[i] == '*': dp[i] = dp[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*"))
"aa", "a." "aaaaaa", "a*"
- Wildcard Pattern Matching
- Matching strings with a wildcard in C#
- How to use wildcard in Python regular expression?
- Matching Versus Searching in Python
- Regular Expression Matching in Python
- Remove matching tuples in Python
- Unix filename pattern matching in Python
- Pattern matching in Python with Regex
- Template matching using OpenCV in Python
- Unix filename pattern matching in Python (fnmatch)
- Prefix matching in Python using pytrie module
- Count of elements matching particular condition in Python
- How to use % wildcard correctly in MySQL?
- Matching Graph