Bhaskar vedula
Bhaskar vedula

Reputation: 93

Python re.search string search for open and close bracket []

Can someone explain me why my regex is not getting satisfied for below regex expression. Could someone let me know how to overcome and check for [] match.

>>> str = li= "a.b.\[c\]"
>>> if re.search(li,str,re.IGNORECASE):
...    print("Matched")
...
>>>
>>> str = li= r"a.b.[c]"
>>> if re.search(li,str,re.IGNORECASE):
...    print("Matched")
...
>>>

If I remove open and close brackets I get match

>>> str = li= 'a.b.c'
>>> if re.search(li,str,re.IGNORECASE):
...    print("matched")
...
matched

Upvotes: 0

Views: 171

Answers (2)

Bharel
Bharel

Reputation: 26901

You are attempting to match the string a.b.\\[c\\] instead of a.b.[c].
Try this:

import re
li= r"a\.b\.\[c\]"
s = "a.b.[c]"
if re.search(li, s, re.IGNORECASE):
    print("Matched")

re.IGNORECASE is not needed in here by the way.

Upvotes: 4

Ren
Ren

Reputation: 2946

You can try the following code:

import re
str = "a.b.[c]"
if re.search(r".*\[.*\].*", str):
   print("Matched")

Output:

Matched

Upvotes: 0

Related Questions