将已编译的正则表达式转换为字符串

时间:2018-01-16 14:27:47

标签: regex go

我在Go方面没有太多经验,但基本上我想在使用它后在屏幕上打印我的正则表达式。我在Google上找不到任何东西。这似乎很容易做,但我尝试了几件事而没有其他工作。

var swagger_regex = regexp.MustCompile(`[0-9][.][0-9]`)
.... some code here ....
fmt.Println("Your '_.swagger' attribute does not match " + string(swagger_regex))

1 个答案:

答案 0 :(得分:5)

regexp.Regexp类型有一个Regexp.String()方法可以完全执行此操作:

  

String返回用于编译正则表达式的源文本。

您甚至不必手动调用它,因为fmt包检查并调用String()方法,如果传递的值的类型有它。

示例:

r := regexp.MustCompile(`[0-9][.][0-9]`)
fmt.Println("Regexp:", r)

// If you need the source text as a string:
s := r.String()
fmt.Println("Regexp:", s)

输出(在Go Playground上尝试):

Regexp: [0-9][.][0-9]
Regexp: [0-9][.][0-9]