
- 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
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 −
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
- Related Articles
- Wildcard Pattern Matching
- Wildcard matching of string JavaScript
- Matching strings with a wildcard in C#
- How to use wildcard in Python regular expression?
- Matching Versus Searching in Python
- Remove matching tuples in Python
- Regular Expression Matching 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
- Python – Remove Dictionaries with Matching Values
- How to use % wildcard correctly in MySQL?
