Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match a pattern (from capture) before a capture group

I have to match text with this scheme:

  • capture [\w-/]* which are not ['] (\1)
  • capture [']+ which follow (\2)
  • and replace \2\1\2 with \1

Example:

my input text is: l''''text'''
the right output is: l'text

I've tried with:

re.sub(r"(\5)(?=((([\w\-\/](?<!'))+)('+)))", r"\2", text)
like image 279
Nicholas Roveda Avatar asked Nov 26 '25 13:11

Nicholas Roveda


1 Answers

You could match the previously matched quotes after the string:

('+)([\w/-]+)\1

The \1 matches the exact same text group 1 matched.

Online demo at https://regex101.com/r/zQ0hM2/2.

Python session demo:

>>> import re
>>> text = "l''''text'''"
>>> re.sub(r'''('+)([\w/-]+)\1''', r'\2', text)
"l'text"
like image 165
Martijn Pieters Avatar answered Nov 29 '25 03:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!