[英]Regex with square brackets
I need to remove substring of a string bounded by the square brackets [
and ]
.我需要删除以方括号[
和]
为界的字符串的 substring 。 This thread here shows how to do that with an example of <...>
.这个线程在这里展示了如何用<...>
的例子来做到这一点。
My example:我的例子:
import re
s = "something something [1] another thing"
re.sub('[[^]]+]', '', s)
This is the output:这是 output:
<input>:1: FutureWarning: Possible nested set at position 1
'something something [1] another thing'
The expected output is something something another thing
.预期的 output 是something something another thing
。
How to regex in similar code dealing with square brackets?如何在处理方括号的类似代码中进行正则表达式?
Escape the literal brackets:转义文字括号:
re.sub(r'\[[^\]]+\]', '', s)
This uses a raw string as without it the backslashes themselves would need to be escaped:这使用原始字符串,因为没有它,反斜杠本身需要转义:
re.sub('\\[[^\\]]+\\]', '', s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.