I need to search a string within another string with exact match and without spaces in Python. For example searching string2 in string1 as below should be True (or a match, then I can convert it to True)
string1="car blue car"
or string1="blue car"
or string1="car blue"
string2="blue"
searching below should be False
string1="car bluea window "
string2="blue"
My string2 can be anywhere within the string1. I just need the exact matches. This also goes for digits. For example, below should be True
string1="blue 300 cars"
string2="300"
but this should be False
string1="blue 30012 cars"
string2="300
Built-in methods like contains or in do not work because they find the strings eventhough they are not exact matches. Regex search might seem like the solution but I couldn't find a successful regex expression to define such a case in re.search()
You can use this regex \b{}\b
to solve this issue, for example, your code can look like this:
import re
def exact_match(string1, string2):
pattern = r'\b{}\b'.format(string2)
match = re.search(pattern, string1)
return bool(match)
For example here
\b
matches a word boundary.{}
is a placeholder for a string that will be inserted into the pattern. This allows you to create a regex pattern dynamically based on the value of a variable.Note: if you have special characters used by the regex, you have to escape them by re.escape()
:
match = re.search(pattern, re.escape(string1))