0

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

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44

2 Answers2

1

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


  • The \b matches a word boundary.
  • The {} 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))
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Thanks, I revised it a bit to fit it in my loop but works like a charm. For reference, in case anyone is looking, in terms of performance, having a function and calling it explicitly is faster than doing it as a list comprehension than calling any() to have True or False. It turns out any() has to go through each iteration again after map generator, which slows it down. I was surprised to see that – ControltheAI Mar 11 '23 at 22:02
1

If your string1 contain ' ' as you have given in the example, then:

string1="car blue car"
string2="blue"

string2 in string1.split()    # split will do ['car', 'blue', 'car']
#True 

string1="car blue car"
string2="blue"

string2 in string1.split()
#False

string1="blue 300 cars"  
string2="300"

string2 in string1.split()
#True

string1="blue 30012 cars"  
string2="300

string2 in string1.split()
#False
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44