如何删除仅包含字符串而不是特殊字符的方括号

时间:2018-10-08 06:45:10

标签: python regex

这是我的文字

(he needs to buy him an) [/-] (.) this rabbit <I> [/] is (..) woke  up (...) (be)cause he needs to go home with his father .

所需的输出是

he needs to buy him an [/-] (.) this rabbit <I> [/] is (..) woke    up (...) because he needs to go home with his father .

3 个答案:

答案 0 :(得分:1)

尝试一下:

\((?=[A-z])|(?<=[A-z])\)

我同时使用了正向超前(?= )和正向超前(?<= )来匹配其中带有字符串的括号。

  • 正向超前(?= )

  • 正向(?<= )后面

  • [A-z]仅匹配字符串

演示:https://regex101.com/r/pc3JDu/1/

答案 1 :(得分:1)

这是一种方法,它对re.sub进行了两次调用:

input = "(he needs to buy him an) [/-] (.) this rabbit <I> [/] is (..) woke [BLAH] up (...) (be)cause he needs to go home with his father ."
output = re.sub(r'\[([A-Za-z0-9]+?)\]', '\\1', re.sub(r'\(([A-Za-z0-9]+?)\)', '\\1', input))

Demo

这与模式\[([A-Za-z0-9]+)\]\(([A-Za-z0-9]+)\)匹配,然后仅替换括号或方括号内的内容。

答案 2 :(得分:0)

re.sub('\(\w\)', '', s)

是-是您的字符串

'\ w'-匹配单词的正则表达式