如何在 Go 中将正则表达式与反向引用匹配? [英] How to match a regex with backreference in Go?

查看:29
本文介绍了如何在 Go 中将正则表达式与反向引用匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要匹配在我的 Go 代码中使用反向引用(例如 1)的正则表达式.

I need to match a regex that uses backreferences (e.g. 1) in my Go code.

这并不容易,因为在 Go 中,官方正则表达式包 使用 RE2 引擎,具有 选择不支持反向引用(以及其他一些鲜为人知的功能),这样可以保证线性时间执行,从而避免 正则表达式拒绝服务攻击.启用反向引用支持不是 RE2 的选项.

That's not so easy because in Go, the official regexp package uses the RE2 engine, one that have chosen to not support backreferences (and some other lesser-known features) so that there can be a guarantee of linear-time execution, therefore avoiding regex denial-of-service attacks. Enabling backreferences support is not an option with RE2.

在我的代码中,不存在被攻击者恶意利用的风险,我需要反向引用.

In my code, there is no risk of malicious exploitation by attackers, and I need backreferences.

我该怎么办?

推荐答案

在这里回答我自己的问题,我使用 golang-pkg-pcre,它使用支持反向引用的 libpcre++、perl 正则表达式.API 不一样.

Answering my own question here, I solved this using golang-pkg-pcre, it uses libpcre++, perl regexes that do support backreferences. The API is not the same.

这篇关于如何在 Go 中将正则表达式与反向引用匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆