简体   繁体   English

在 Python 的 re.sub() 的 Javascript `replace()` 中是否有等同于 $` 的东西?

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

In JS , you can use 在 JS中,你可以使用

  • $` Inserts the portion of the string that precedes the matched substring. $`插入匹配的 substring 之前的字符串部分。

  • $' Inserts the portion of the string that follows the matched substring. $'插入匹配的 substring 之后的字符串部分。

To get the substring before and after the match.获得比赛前后的substring。

Is there an equivalent of this in Python's re.sub() ? Python 的re.sub()中是否有与此等效的内容?

Instead of a replacement string, you can pass a function to re.sub .您可以将 function 传递给re.sub ,而不是替换字符串。 The function will receive a match object, and should return the replacement for the match. function 将收到一场比赛 object,并应返回比赛的替代品。

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 .在 function 中,您可以使用match.start()match.end()获取原始字符串中匹配项的开始和结束索引,并match.string获取传递给re.sub的原始字符串。 Thus,因此,

match.string[:match.start()]

gives the effect of $` , and给出$`的效果,并且

match.string[match.end():]

gives the effect of $' .给出$'的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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