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.

Asked By: Bidur-Khanal

||

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
Answered By: ruohola
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.