[英]I want to escape all characters within square brackets except start and end of that bracket in python using regex
Input: 输入:
[cd ab:12:00][abc-12][abc.c 12][abc]
Desired Output: 所需输出:
[][][][]
You could do this through re.sub
function. 您可以通过
re.sub
函数执行此操作。
>>> s = '[cd ab:12:00][abc-12][abc.c 12][abc]'
>>> re.sub(r'\[[^\]]*\]', r'[]', s)
'[][][][]'
Regex Explanation: 正则表达式说明:
\\[
matches the literal [
symbol. \\[
匹配文字[
符号。 [^\\]]*
negated character class which matches any character but not of ]
, zero or more times. [^\\]]*
否定的字符类,与任何字符匹配,但不匹配]
,零次或多次。 So this matches all the chars present in-between two square brackets. \\]
matches the literal ]
bracket. \\]
与文字[ ]
括号匹配。 So this regex would match all the square brackets block. []
will give you the desired output of removing all the chars present inside the square brackets. []
替换所有匹配的块将为您提供所需的输出,以删除方括号内的所有字符。 You could achieve the same by using lookaround assertions. 您可以通过使用环视断言来达到相同目的。
>>> re.sub(r'(?<=\[)[^\]]*(?=\])', r'', s)
'[][][][]'
Use [^\\[\\]]+
使用
[^\\[\\]]+
Match all except [
and ]
. 匹配除
[
和]
以外的所有字符。 You can replace matches with ""
您可以将匹配项替换为
""
Ex: 例如:
re.sub(r'[^\[\]]+', r'', str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.