2017-07-26 83 views
0

我提取字符串,需要檢查它是否符合特定的模式使用特殊字符正則表達式來找到Python中的比賽

<![any word]>

如果是的話我需要來取代它「」。我想下面的代碼

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

但我得到的輸出作爲

<![if support]> hello 

我希望得到的輸出爲hello。我在這裏做錯了什麼?

回答

4

[]被視爲正則表達式元字符。你需要轉義:

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

作爲simplification(禮貌Wiktor的Stribiżew),你可以躲開第一左括號,縮短你的正則表達式來"<!\[.*?]>"

+1

']'是不是一個字符類之外的特殊的正則表達式運算符。 'R 「」'就足夠了。 –