Skip to content Skip to sidebar Skip to footer

Check Exact Match Of String With Brackets In Another String Python

There are many answers to a similar type of question to mine, but I'm not sure why this isn't working. I've got a very simple example of two strings, where I am checking if one is

Solution 1:

Try to use "replace" to validate brackets and use * to match 0 or more repetitions.

import re

text = "random/path/path_with_brackets[3]"
text = text.replace('[','\[')
search = "test/random/path/path_with_brackets[3]/another_path"if re.search(r".*{}.*".format(text), search, re.IGNORECASE) isnotNone:
    print("text is contained in search")
else:
    print("text not contained in search")

Solution 2:

If you don't need to use regex, you can simply use in:

print(text in search)  # -> True

If you do need to use regex, like if the word boundaries are important, i.e. you don't want random to match inside get_random for example, then you'll need to escape the brackets since they're special; they represent a character set. E.g. [3] matches 3. You can do that with re.escape:

r"\b{}\b".format(re.escape(text))

But then you have another problem: ]/ isn't a word boundary, so \b won't match there. To fix it you can use a similar concept to \b:

r"(?:^|\W)({})(?:$|\W)".format(...)

These are non-capturing groups that match either the start/end of the string or a non-word character.

It also makes sense to put your desired text in a group so that you can retrieve it with .group(1).

Post a Comment for "Check Exact Match Of String With Brackets In Another String Python"