使用python regex删除括号之间的内容 [英] remove content between parentheses using python regex
问题描述
我有一个像 -
{[a] abc (b(c)d)}
我想删除这些括号[]和(())
之间的内容.所以输出应该是 -
I want to remove the content between these bracket [] and (())
. so the output should be -
abc
我删除了括号之间的内容,但无法删除此[]
之间的内容我试过下面的代码 -
I removed the content between parentheses but could not remove the content between this []
I have tried below code -
import re
with open('data.txt') as f:
input = f.read()
line = input.replace("{","")
line = line.replace("}","")
output = re.sub(r'\(.*\)', "", line)
print output
输出是 -
[a] abc
在我的代码中,我首先替换 {}
,然后从 ()
中删除内容.我想在 output = re.sub(r'\(.*\)', "", line)
这一行中添加 \[.*\]
.但找不到办法做到这一点.我还在学习python.所以我正面临这个问题.请帮忙.
In my code first I replace the {}
and then remove the content from ()
. I want to add \[.*\]
in output = re.sub(r'\(.*\)', "", line)
this line . But could not find a way to do this. I am still learning python. So I am facing this problem. please help.
推荐答案
您可以检查字符串是否包含 [
, ]
, (
或 [no_brackets_here]
子串并在匹配时删除它们.
You may check if a string contains [
, ]
, (<no_parentheses_here>)
or [no_brackets_here]
substrings and remove them while there is a match.
import re # Use standard re
s='{[a] abc (b(c)d)}'
rx = re.compile(r'\([^()]*\)|\[[^][]*]|[{}]')
while rx.search(s): # While regex matches the string
s = rx.sub('', s) # Remove the matches
print(s.strip()) # Strip whitespace and show the result
# => abc
查看 Python 演示
它也适用于成对的嵌套 (...)
和 [...]
.
It will also work with paired nested (...)
and [...]
, too.
模式详情
\([^()]*\)
-(
,然后是除(
和) 之外的任何 0+ 个字符
,然后是)
|
- 或\[[^][]*]
-[
,然后是除[
和] 之外的任何 0+ 个字符/code>,然后
]
|
- 或[{}]
- 匹配{
或}
的字符类.
\([^()]*\)
-(
, then any 0+ chars other than(
and)
, and then)
|
- or\[[^][]*]
-[
, then any 0+ chars other than[
and]
, and then]
|
- or[{}]
- a character class matching{
or}
.
这篇关于使用python regex删除括号之间的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!