简体   繁体   English

我想使用正则表达式对方括号内的所有字符进行转义,但在python中该括号的开始和结尾除外

[英]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. 因此,此正则表达式将匹配所有方括号块。 Replacing all the matched blocks with [] 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.

相关问题 使用 SED 或 Python 删除每个 json obj 末尾的所有逗号以及开头和结尾的方括号 - Remove all commas at end of each json obj and square brackets at start and end using either SED or Python 如何在 Python 中使用正则表达式删除右方括号? - How can I remove the closing square bracket using regex in Python? 在Python中带有方括号且没有方括号的列表 - List with square bracket and no brackets in Python 正则表达式选择除方括号[]内的分号外的所有分号 - Regex to select every semicolon except the ones enclosed within Square brackets [] Python 使用 re 在字符之间创建空格,方括号中的字符除外 - Python using re to create spaces between characters except for those in square brackets Python正则表达式在不带括号的括号内打印字符串 - Python regex print string within brackets without the bracket 我想在python中制作支架检查器,它计算错误的括号 - I want to make bracket checker in python that counts the wrong brackets 如何使用 python 中的正则表达式删除除某些特殊字符外的所有特殊字符 - How to remove all special characters except for some, using regex in python 使用 Python(正则表达式)仅在数据框中的方括号中包含数据 - To have data only in square bracket in a data frame using a Python (regex) 在python中,如何使用正则表达式将方括号替换为括号 - In python, how can I use regex to replace square bracket with parentheses
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM