1

Here is my code:

In [1]: import re

In [2]: p = 'zxc(.*?)!(.*?)zxc'

In [3]: s = 'zxc wololo ! ololo zxc'

In [4]: re.sub(pattern=p, repl=r"", string=s)
Out[4]: ''

In [5]: re.sub(pattern=p, repl=r"\1", string=s)
Out[5]: ' wololo '

Expected

zxc wololo !zxc

Question

How to achieve the expected output?

I need to keep 1-st group with "prefix" and "suffix" of pattern. And let's assume that there are more then 2 groups.

Which keyword I should use in repl to achieve the expected result?

1

1 Answer 1

4

You may use a zero width lookaround based regex:

>>> s = 'zxc wololo ! ololo zxc'
>>> print re.sub(r'(?<=zxc)([^!]*!).*?(?=zxc)', r'\1', s)
zxc wololo !zxc

Here:

  • (?<=zxc) is a lookbehind assertion
  • (?=zxc) is a lookahead assertion
  • ([^!]*!) matches and captures substring until ! and following ! in group #1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.