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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Wildcard Substring search
# Using re.search()
import re
      
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_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))) 

chevron_right


Output :

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Wildcard Substring search
# Using re.finditer()
import re
      
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing Substring
sub_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))) 

chevron_right


Output :

The original string is : geeksforgeeks is best for geeks                                                                
The substring match is : best     



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.