正则表达式:如何替换为字符串文字“\1”?

发布于 2024-09-11 14:16:10 字数 345 浏览 4 评论 0原文

我有一个字符串,例如r"a"。我想用字符串 r"\1" 替换每个 r"a",但我的正则表达式引擎不理解这一点。

我尝试过:

  • r"\1" -- 崩溃(无法匹配组 1,因为没有组 1)
  • r"\\1"< /code> -- 崩溃(不知道为什么)

这是我的(专有)正则表达式引擎的限制,还是一个普遍问题?有一个优雅的方法来解决它吗? (例如,我可以将“a”替换为“/1”,然后使用 StrReplace(“/”, r"\" )...但这不太好!)

I have a string, say r"a". I want to replace every r"a" with the string r"\1", but my regex engine does not understand this.

I have tried:

  • r"\1" -- crashes (can't match group 1 because there is no group 1)
  • r"\\1" -- crashes (not sure why)

Is this a limitation of my (proprietary) regex engine, or is it a general problem? Is there an elegant way of solving it? (I could e.g. replace "a" by "/1" and then StrReplace( "/", r"\" )... but that's not nice!)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枕花眠 2024-09-18 14:16:10

正确的方法是使用 r"\\1" 作为替换字符串。因此,如果您的专有正则表达式引擎/语言因 \\ 而卡住,您应该修复此错误。

如果您看一下您的示例,您根本不需要正则表达式引擎。但也许这个例子比实际要求更简单......

The correct way would be to use r"\\1" as a replace string. So if your proprietary regex engine/language chokes on a \\, you should fix this bug.

If you look at your example, you don't need a regex engine at all. But perhaps the example is simpler than the actual requirement...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文