doujiang2020 2018-01-16 14:27
浏览 131
已采纳

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

I don't have much experience in Go, but basically I want to print my regex on the screen after using it. I cant find anything on Google. This seems something rather easy to do but I have tried several things and nothing else worked.

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

1条回答 默认 最新

  • dongliang2058 2018-01-16 14:30
    关注

    The regexp.Regexp type has a Regexp.String() method which does this exactly:

    String returns the source text used to compile the regular expression.

    You don't even have to call it manually, as the fmt package checks and calls the String() method if the type of the passed value has it.

    Example:

    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)
    

    Output (try it on the Go Playground):

    Regexp: [0-9][.][0-9]
    Regexp: [0-9][.][0-9]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?