duanlu6114 2017-12-11 12:18
浏览 779

如何取消转义的正则表达式?

I'm looking for the reverse of regexp.QuoteMeta. Is it there a such function?

I've tried to manually unescape it using strings.Replace("\", "", -1) but this is prone to error/unreliable as it doesn't work in all the cases(i.e. on excessive escaping or unicode).

I also tried to add some quotes and use strconv.Unquote (e.g. strconv.Unquote("+ "https:\/\/ad.doubleclick.net" +") ) but it errors out.

  • 写回答

1条回答 默认 最新

  • drelgkxl93433 2017-12-11 15:35
    关注

    Parse the string with the regexp/syntax package to get the unquoted string:

    func unquoteMeta(s string) (string, error) {
        r, err := syntax.Parse(s), 0)
        if err != nil {
            return "", err
        }
        if r.Op != syntax.OpLiteral {
            return "", errors.New("not a quoted meta")
        }
        return string(r.Rune), nil
    }
    

    playground example

    评论

报告相同问题?