1
votes

All a specific letter, let's say 'A', needs to be replaced in all parentheses.

For example,

A. (AbbAAbb) .A. (bbAbbAbA) .A. (bbbbAbbbb)

I want to replace all 'A' in the parenthese with '' to end up like this:

A. (bbbb) .A. (bbbbb) .A. (bbbbbbbb)

Any possible to do this in only regular expression?

2
You want to remove it? - cs95
You're saying random numbers of an element in your title, but all of a specific element in your question. Please post a desired output - user3483203
No, not pure regex in Python re, but you may use re.sub(r'\([^()]+\)', lambda x: x.group().replace('A', ''), s) if you want to remove all A inside (...). The same can be done with just a regex if you use PyPi regex module, regex.sub(r'(?<=\([^()]*)A(?=[^()]*\))', '', s). - Wiktor Stribiżew
@WiktorStribiżew you should post that as an answer, you had it here first - user3483203
Need a callback to do this. But, it's really the simplest thing in regexland to do. Just match \(([^()}+)\) . In the callback just replace the a's then return the new string with paren's around it. Btw, don't use assertions, it will slow the regex down significantly. - user557597

2 Answers

6
votes

There is a common workaround for such situations - no unbalanced / nested parentheses (as they are) should exist. You look for As that follow a closing parenthesis without matching a parenthesis:

A(?=[^)(]*\))

Live demo

Python code:

re.sub(r"A(?=[^)(]*\))", "", str)
6
votes

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.