简体   繁体   中英

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.

To get the substring before and after the match.

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

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, andmatch.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 $' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM