Python – Wildcard Substring search
Last Updated :
09 Apr, 2023
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
import re
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
sub_str = '..st'
temp = re.compile(sub_str)
res = temp.search(test_str)
print("The substring match is : " + str(res.group(0)))
|
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.
Python3
import re
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
sub_str = '..st'
temp = re.compile(sub_str)
res = temp.search(test_str)
print("The substring match is : " + str(res.group(0)))
|
Output :
The original string is : geeksforgeeks is best for geeks
The substring match is : best
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Method #3 : Here’s another approach that uses the re library and the re.findall method. It is similar to the re.search method, but re.findall returns a list of all non-overlapping matches as separate strings.
Python3
import re
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
sub_str = '..st'
temp = re.compile(sub_str)
res = temp.findall(test_str)
print("The substring match(es) are: " + str(res))
|
Output
The original string is : geeksforgeeks is best for geeks
The substring match(es) are: ['best']
The time and space complexity for this approach is the same as the previous methods:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using split(),replace(),endswith(),join() methods
Approach
- Splitted the given string using split()
- Replaced . with empty string in sub_str(using replace())
- Initiated a for loop to traverse the list
- Checked whether the length of element is equal to initial substring length and whether the element endswith replaced substring(using endswith())
- If True append such elements to output list
- Finally joined the output and displayed it(using join())
Python3
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
sub_str = '..st'
x=test_str.split()
res=[]
y=len(sub_str)
sub_str=sub_str.replace(".","")
for i in x:
if len(i)==y and i.endswith(sub_str):
res.append(i)
print("The substring match is : " + "".join(res))
|
Output
The original string is : geeksforgeeks is best for geeks
The substring match is : best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using string slicing and a list comprehension
1. Initialize the string and the pattern to search for.
2. Print the original string.
3. Use a list comprehension to create a list of all substrings that match the pattern.
a. For each possible starting index i in the original string, extract a substring of length equal to the length of the pattern.
b. Check if each character in the substring matches the corresponding character in the pattern, or if the pattern character is a wildcard “.”.
c. If all characters match or are wildcards, add the substring to the list of matches.
4. If there is at least one match, print the first one.
Python3
test_str = 'geeksforgeeks is best for geeks'
sub_str = '..st'
print("The original string is : " + str(test_str))
matches = [test_str[i:i+len(sub_str)] for i in range(len(test_str) - len(sub_str) + 1) if all(a == b or b == '.' for a, b in zip(test_str[i:i+len(sub_str)], sub_str))]
if len(matches) > 0:
print("The substring match is : " + matches[0])
|
Output
The original string is : geeksforgeeks is best for geeks
The substring match is : best
The time complexity : O(nm), where n is the length of the original string test_str and m is the length of the substring sub_str. The code uses a list comprehension to iterate over all possible starting indices of the substring and check if the characters match the pattern using the zip function. Since the zip function has a time complexity of O(m) and the list comprehension is repeated n-m+1 times, the overall time complexity is O(nm).
The auxiliary space :O(k), where k is the number of substring matches found. This is because the code stores all matching substrings in the matches list. Since the maximum number of matching substrings is limited to the number of possible starting indices, which is n-m+1, the space complexity is O(n-m+1), which is equivalent to O(n).
Method #6: Using list comprehension and string comparison without zip()
Steps:
- Use a list comprehension to iterate through the input string and generate a list of substrings that match the given wildcard pattern. In this case, we use string slicing and endswith() method for comparison.
- Extract the matched substring from the list of matches. We take the first match from the list, if any, otherwise set the result to None.
- Print the result.
Python3
test_str = 'geeksforgeeks is best for geeks'
print("The original string is : " + str(test_str))
sub_str = '..st'
matches = [test_str[i:i+len(sub_str)] for i in range(len(test_str)-len(sub_str)+1) if test_str[i:i+len(sub_str)].endswith(sub_str[-1])]
res = matches[0] if matches else None
print("The substring match is : " + str(res))
|
Output
The original string is : geeksforgeeks is best for geeks
The substring match is : best
Time Complexity: O(n), where n is the length of the test string.
Auxiliary Space: O(1).
Similar Reads
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.s
6 min read
Python - String till Substring
Sometimes, more than finding a substring, we might need to get the string that is occurring before the substring has been found. Let’s discuss certain ways in which this task can be performed. Method #1 : Using partition() The partition function can be used to perform this task in which we just retu
4 min read
Python Extract Substring Using Regex
Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
2 min read
Python - Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
2 min read
Python | Word Stretch
Write a program to get all possibilities (in sorted order) for stretching a word to the given size. If the list of required indices is passed, then only those combinations present at those indices should be returned. If the required indices are null, then all the combinations have to be returned.Exa
3 min read
Python - Test substring order
Given two strings, check if substring characters occur in correct order in string. Input : test_str = 'geeksforgeeks', K = 'sees' Output : True Explanation : "s" after that "ee" and then "s" is present in order in string 1. Input : test_str = 'geeksforgeeks', K = 'seef' Output : False Explanation :
5 min read
How to Remove a Substring in Python?
In Python, removing a substring from a string can be achieved through various methods such as using replace() function, slicing, or regular expressions. Depending on your specific use case, you may want to remove all instances of a substring or just the first occurrence. Let’s explore different ways
2 min read
Python | Word location in String
Word location in String problem in Python involves finding the position of a specific word or substring within a given string. This problem can be approached using various methods in Python, such as using the find(), index() methods or by regular expressions with the re module. Using str.find()str.f
4 min read
Python - Extract string between two substrings
Given a string and two substrings, write a Python program to extract the string between the found two substrings. In Python we have multiple methods and ways to extract the line between two strings. Input: "Gfg is best for geeks and CS" sub1 = "is" ' sub2 = "and" Output: best for geeks Explanation:
6 min read
Python | Ways to count number of substring in string
Given a string and a substring, write a Python program to find how many numbers of substrings are there in the string (including overlapping cases). Let's discuss a few methods below. Method #1: Using re.findall() Method C/C++ Code # Python code to demonstrate # to count total number # of substring
4 min read
Python - Selectively Split in Strings
Sometimes, while working with Python strings, we may have to perform a split. Not sometimes, normal one, depending on deliminator but something depending upon programming constructs like elements, numbers, words etc and segregate them. Lets discuss a way in which this task can be solved. Method : Us
3 min read
Python | Get matching substrings in string
The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension Using l
6 min read
Python | Removing Initial word from string
During programming, sometimes, we can have such a problem in which it is required that the first word from the string has to be removed. These kinds of problems are common and one should be aware about the solution to such problems. Let's discuss certain ways in which this problem can be solved. Met
4 min read
Python - Get Nth word in given String
Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
4 min read
Python - Phrase removal in String
Sometimes, while working with Python strings, we can have a problem in which we need to extract certain words in a string excluding the initial and rear K words. This can have application in many domains including all those include data. Lets discuss certain ways in which this task can be performed.
2 min read
Python - Possible Substring count from String
Given target string and argument substring, count how many substrings can be constructed using string characters, repetitions not allowed. Input : test_str = "geksefokesgergeeks", arg_str = "geeks" Output : 3 Explanation : "geeks" can be created 3 times using string characters. Input : test_str = "g
4 min read
Python | Substring Key match in dictionary
Sometimes, while working with dictionaries, we might have a use case in which we are not known the exact keys we require but just a specific part of keys that we require to fetch. This kind of problem can arise in many applications. Let's discuss certain ways in which this problem can be solved. Met
9 min read
Python - Filter Strings within ASCII range
Given ASCII or alphabetical range, filter strings are found in a particular range. Input : test_list = ["gfg", "is", "best", "for", "geeks"], strt_asc, end_asc = 105, 115 Output : ['is'] Explanation : i has 105, and s has 115, which is in range ASCII values.Input : test_list = ["gfg", "is", "best",
3 min read
Python - Test if Substring occurs in specific position
Sometimes, while working with python strings, we can have a problem in which we need to test occurrence of substring. There is straight forward way to test this. But sometimes, we have a more specific problem in which we need to test if substring occurs at that particular position. Let's discuss cer
6 min read