Created
May 27, 2020 11:19
-
-
Save lithdew/662510e83c416f731828988716189211 to your computer and use it in GitHub Desktop.
Unescape strings in Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func unescape(s string) (string, error) { | |
if !strings.ContainsRune(s, '\\') && utf8.ValidString(s) { | |
return s, nil | |
} | |
tmp := make([]byte, utf8.UTFMax) | |
buf := make([]byte, 0, 3*len(s)/2) | |
for len(s) > 0 { | |
c, mb, t, err := strconv.UnquoteChar(s, '"') | |
if err != nil { | |
return "", err | |
} | |
s = t | |
if c < utf8.RuneSelf || !mb { | |
buf = append(buf, byte(c)) | |
} else { | |
n := utf8.EncodeRune(tmp[:], c) | |
buf = append(buf, tmp[:n]...) | |
} | |
} | |
return string(buf), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment