sha*_*han 1 python regex string
我正在提取一个字符串,需要检查它是否遵循特定模式
<![any word]>
如果是这样我需要用""替换它.我正在尝试以下代码
string1 = "<![if support]> hello"
string = re.sub(re.compile("<![.*?]>"),"",string1)
print(string)
Run Code Online (Sandbox Code Playgroud)
但是我得到了输出
<![if support]> hello
Run Code Online (Sandbox Code Playgroud)
我希望输出为hello.我在这做错了什么?
[并]在regex中被视为元字符.你需要逃脱它们:
In [1]: re.sub(re.compile("<!\[.*?\]>"), "", "<![if support]> hello")
Out[1]: ' hello'
Run Code Online (Sandbox Code Playgroud)
作为简化(由WiktorStribiżew提供),你可以逃脱第一个左边的paren,缩短你的正则表达式"<!\[.*?]>".