有没有办法在正则表达式中转义Go字符串?

huangapple go评论81阅读模式
英文:

Any way to escape a Go string in a regular expression?

问题

我想要匹配 ^(@|\s)*{{string}}:?,其中{{string}}是动态定义的。它可能包含句点、破折号和其他任意字符,我真的需要对它进行转义。

PHP 提供了一个 preg_quote 方法,可以安全地转义所有特殊字符。我想知道 Go 是否提供了类似的功能。

英文:

I'm wanting to match ^(@|\s)*{{string}}:? whereas {{string}} is dynamically defined. It may have periods and dashes and any number of things in it and I really need for it to be escaped.

PHP provides a preg_quote method that escapes all special characters safely. I was wondering if Go provides any sort of analog.

答案1

得分: 65

regexp.QuoteMeta完成了这个任务。

英文:

regexp.QuoteMeta does the deed.

huangapple
  • 本文由 发表于 2014年12月11日 12:46:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/27415532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定