diff options
author | clsr <clsr@clsr.net> | 2021-12-23 01:54:47 +0000 |
---|---|---|
committer | clsr <clsr@clsr.net> | 2021-12-23 02:51:49 +0000 |
commit | 43428e759d9fbc5a319c2b929bfb4469938cc386 (patch) | |
tree | 1ee452ff23249bf10653481599f8639aa46ceb25 /simpletext.go | |
parent | 690a7183d7eca35b59e23e556b0c6492df08ffa5 (diff) | |
download | cnm-go-43428e759d9fbc5a319c2b929bfb4469938cc386.tar.gz cnm-go-43428e759d9fbc5a319c2b929bfb4469938cc386.zip |
Diffstat (limited to 'simpletext.go')
-rw-r--r-- | simpletext.go | 32 |
1 files changed, 31 insertions, 1 deletions
diff --git a/simpletext.go b/simpletext.go index 4d86d6d..00d82ec 100644 --- a/simpletext.go +++ b/simpletext.go @@ -70,7 +70,9 @@ func CollapseWhitespace(raw string) string { var escapeRe = regexp.MustCompile(`[\t\n\f\r\\\x00]|^ | $| `) -// Escape escapes whitespace, backslash and and U+0000 within s. +// Escape escapes whitespace, backslash and U+0000 within s. +// +// Only leading, trailing or multiple consecutive spaces are escaped. func Escape(s string) string { return escapeRe.ReplaceAllStringFunc(s, func(match string) string { switch match { @@ -115,6 +117,34 @@ func EscapeSpace(s string) string { }) } +var escapeAllRe = regexp.MustCompile(`[\t\n\f\r\\\x00 ]`) + +// EscapeAll escapes all whitespace, backslash and and U+0000 within s. +// +// Unlike Escape, all spaces are escaped, not just ones that would be collapsed +// into one. +func EscapeAll(s string) string { + return escapeAllRe.ReplaceAllStringFunc(s, func(match string) string { + switch match { + case "\t": + return `\t` + case "\n": + return `\n` + case "\f": + return `\f` + case "\r": + return `\r` + case "\\": + return `\\` + case "\x00": + return `\x00` + case " ": + return `\ ` + } + return match // this shouldn't happen + }) +} + var escapeNonspaceRe = regexp.MustCompile(`[\f\r\\\x00]`) // EscapeNonspace works like Escape, except it does not escape spaces, tabs and |