Python – Wildcard Substring search
Sometimes, while working with Python Strings, we have problem in which, we need to search for substring, but have some of characters missing and we need to find the match. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using re.search()
This is one of the way in which this task can be performed. In this, we feed the regex compile with the substring and search for it using main string in search().
# Python3 code to demonstrate working of # Wildcard Substring search# Using re.search()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing Substringsub_str = '..st' # Wildcard Substring search# Using re.search()temp = re.compile(sub_str) res = temp.search(test_str) # printing result print("The substring match is : " + str(res.group(0))) |
The original string is : geeksforgeeks is best for geeks The substring match is : best
Method #2 : Using re.finditer()
This is yet another way to solve this problem. In this, we can also extract the position of match if required.
# Python3 code to demonstrate working of # Wildcard Substring search# Using re.finditer()import re # initializing stringtest_str = 'geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # initializing Substringsub_str = '..st' # Wildcard Substring search# Using re.finditer()temp = re.compile(sub_str) res = temp.search(test_str) # printing result print("The substring match is : " + str(res.group(0))) |
The original string is : geeksforgeeks is best for geeks The substring match is : best



.png)