Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an equivalent of $` in Javascript's `replace()` for Python's re.sub()?

In JS, you can use

  • $` Inserts the portion of the string that precedes the matched substring.

  • $' Inserts the portion of the string that follows the matched substring.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

To get the substring before and after the match.

Is there an equivalent of this in Python’s re.sub()?

>Solution :

Instead of a replacement string, you can pass a function to re.sub. The function will receive a match object, and should return the replacement for the match.

Within the function, you can use match.start() and match.end() to get the start and end indices of the match in the original string, and match.string to get the original string passed to re.sub. Thus,

match.string[:match.start()]

gives the effect of $`, and

match.string[match.end():]

gives the effect of $'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading