Go语言中如何将已编译正则表达式转换为字符串并打印?
Hey there! Let's get your regex pattern printing correctly in Go. The issue here is that you're trying to convert a *regexp.Regexp object directly to a string, which doesn't give you the actual regex pattern—it's converting the underlying struct representation instead, which is why you're getting unexpected output.
The Correct Approach
The regexp.Regexp type has a built-in String() method that returns the original regex pattern you used to compile it. Here's how to adjust your code:
package main import ( "fmt" "regexp" ) func main() { var swagger_regex = regexp.MustCompile(`[0-9][.][0-9]`) // ... your other code here ... fmt.Println("Your '_.swagger' attribute does not match " + swagger_regex.String()) }
Why Your Original Code Failed
When you do string(swagger_regex), you're forcing a type conversion on a pointer to a regexp.Regexp struct. Go doesn't know how to turn that struct into a meaningful string, so it's just interpreting the raw memory bytes as a string—resulting in garbage or unreadable text. Using the String() method, however, is designed explicitly to return the regex pattern you defined, so it's the right tool for the job.
Alternatively, you can also use fmt.Printf with the %s verb, which will automatically call the String() method for you:
fmt.Printf("Your '_.swagger' attribute does not match %s\n", swagger_regex)
Either way, you'll get the expected regex pattern ([0-9][.][0-9]) printed to the screen instead of the incorrect output you were seeing before.
内容的提问来源于stack exchange,提问作者Matias Barrios

