I have a text file like -
{[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
The output is -
[a] abc
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.
You may check if a string contains
[
,]
,(<no_parentheses_here>)
or[no_brackets_here]
substrings and remove them while there is a match.See the Python demo
It will also work with paired nested
(...)
and[...]
, too.Pattern details
([^()]*)
-(
, 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}
.