golang如何用正则表达式组替换字符串?

时间:2017-04-24 10:48:04

标签: regex go regex-group

我想使用正则表达式组替换#include <iostream> #include <memory> struct Base { std::shared_ptr< Base > Clone() const { std::cout << "Base::Clone\n"; return CloneImplementation(); } private: virtual std::shared_ptr< Base > CloneImplementation() const { std::cout << "Base::CloneImplementation\n"; return std::shared_ptr< Base >(new Base(*this)); } }; struct Derived : public Base { std::shared_ptr< Derived > Clone() const { std::cout << "Derived::Clone\n"; return std::static_pointer_cast< Derived >(CloneImplementation()); } private: virtual std::shared_ptr< Base > CloneImplementation() const override { std::cout << "Derived::CloneImplementation\n"; return std::shared_ptr< Derived >(new Derived(*this)); } }; int main() { Base *b = new Derived; b->Clone(); } 中的字符串,就像跟在golang中一样:

python

那么如何在golang中实现呢?

1 个答案:

答案 0 :(得分:7)

替换使用$1$2等。例如:

re := regexp.MustCompile(`(foo)`)
s := re.ReplaceAllString("foo", "$1$1")
fmt.Println(s)

游乐场:https://play.golang.org/p/ZHoz-X1scf

文档:https://golang.org/pkg/regexp/#Regexp.ReplaceAllString