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

Mat*_*ios 2 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))
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 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)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上试试):

Regexp: [0-9][.][0-9]
Regexp: [0-9][.][0-9]
Run Code Online (Sandbox Code Playgroud)