Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

python - Replace paticular element inside all parentheses

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...