How do I match string using regex when there is small bracket in string?
Question:
Suppose, I have two strings:
A = 'Ecology (miscellaneous)'
B = 'Ecology (miscellaneous)'
I want to find whether they match or not using regular expressions.if (A == B)
works fine, but, I want to use regex.
re.match (A,B)
This does not work because of small brackets in the string. What is the best way to do it?. I am not used to with regular expressions; I am learning.
Answers:
You can simply use re.escape
on the one string you want to treat as the pattern and just pass the other as is:
import re
A = 'Ecology (miscellaneous)'
B = 'Ecology (miscellaneous)'
print(bool(re.match(re.escape(A), B)))
Output:
True
Suppose, I have two strings:
A = 'Ecology (miscellaneous)'
B = 'Ecology (miscellaneous)'
I want to find whether they match or not using regular expressions.if (A == B)
works fine, but, I want to use regex.
re.match (A,B)
This does not work because of small brackets in the string. What is the best way to do it?. I am not used to with regular expressions; I am learning.
You can simply use re.escape
on the one string you want to treat as the pattern and just pass the other as is:
import re
A = 'Ecology (miscellaneous)'
B = 'Ecology (miscellaneous)'
print(bool(re.match(re.escape(A), B)))
Output:
True