Replace Paticular Element Inside All Parentheses
Solution 1:
There is a common workaround for such situations - no unbalanced / nested parentheses (as they are) should exist. You look for A
s that follow a closing parenthesis without matching a parenthesis:
A(?=[^)(]*\))
Python code:
re.sub(r"A(?=[^)(]*\))", "", str)
Solution 2:
With Python re
, it is not possible to just use a plain regex, you may use a replacement callback method inside re.sub
.
If you want to remove all A
inside (...)
you may use
re.sub(r'\([^()]+\)', lambda x: x.group().replace('A', ''), s)
Here, \([^()]+\)
matches (
, 1+ chars other than (
and )
, and then a )
, passes the match value to the lambda expression (x
) and the match text is accessible via m.group()
(if you define capturing groups, you may access them usign .group(n)
). With a mere replace('A', '')
, you achieve what you need.
See the Python demo
The same can be done with a plain regex if you use PyPi regex module:
regex.sub(r'(?<=\([^()]*)A(?=[^()]*\))', '', s)
See this Python demo.
Here, the lookarounds are used, and this works because PyPi supports infinite-width lookbehinds.
Post a Comment for "Replace Paticular Element Inside All Parentheses"