How to unescape escaped regex?

问题内容:

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.

问题评论:

    
No there is no such function. Did you take a look at a Regexps string method?
    
String() doesn’t seem to work … it prints the escaped string (https:\/\/ad.doubleclick.net)
– user7425610
3 hours ago
    
The regexp.QuoteMeta function will not return the string https:\/\/ad.doubleclick.net for any input. Please update the question with the actual strings and code.

答案:

答案1:

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

r, err := syntax.Parse(regexp.QuoteMeta("https://ad.doubleclick.net"), 0)
if err != nil {
    log.Fatal(err)
}
if r.Op != syntax.OpLiteral {
    log.Fatal("not a literal string")
}
unquoted := string(r.Rune)

playground example

答案评论:

原文地址:

https://stackoverflow.com/questions/47752821/how-to-unescape-escaped-regex

Tags:,

添加评论

友情链接:蝴蝶教程