1

I am extracting a string and need to check whether it follows a particular pattern

<![any word]>

if so I need to replace it with "". I am trying the following code

string1 = "<![if support]> hello"
string = re.sub(re.compile("<![.*?]>"),"",string1)
print(string)

But I am getting the output as

<![if support]> hello 

I wish to get the output as hello. What am I doing wrong here?

cs95
  • 379,657
  • 97
  • 704
  • 746
shan
  • 467
  • 4
  • 9
  • 20

1 Answers1

6

[ and ] are treated as meta characters in regex. You'll need to escape them:

In [1]: re.sub(re.compile("<!\[.*?\]>"), "", "<![if support]> hello")
Out[1]: ' hello'

As a simplification (courtesy Wiktor Stribiżew), you can escape just the first left paren, shortening your regex to "<!\[.*?]>".

cs95
  • 379,657
  • 97
  • 704
  • 746