Skip to content

Instantly share code, notes, and snippets.

@spiegel-im-spiegel
Last active May 27, 2019 12:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save spiegel-im-spiegel/06da7b156d5e68d84abc0196e99a38fa to your computer and use it in GitHub Desktop.
Go 言語で改行コードを変換する(正規表現以外の解) ref: https://qiita.com/spiegel-im-spiegel/items/f1cc014ecb233afaa8af
package main
import (
"fmt"
"regexp"
)
var regxNewline = regexp.MustCompile(`\r\n|\r|\n`) //throw panic if fail
func convNewline(str, nlcode string) string {
return regxNewline.Copy().ReplaceAllString(str, nlcode)
}
func main() {
before := "あ\n\r\r\nえ"
fmt.Printf("%U\n", []rune(before))
after := convNewline(before, "\n")
fmt.Printf("%U\n", []rune(after))
}
[U+3042 U+000A U+3044 U+000D U+3046 U+000D U+000A U+3048]
[U+3042 U+000A U+3044 U+000A U+3046 U+000A U+3048]
package main
import (
"fmt"
"strings"
)
func convNewline(str, nlcode string) string {
return strings.NewReplacer(
"\r\n", nlcode,
"\r", nlcode,
"\n", nlcode,
).Replace(str)
}
func main() {
before := "あ\n\r\r\nえ"
fmt.Printf("%U\n", []rune(before))
after := convNewline(before, "\n")
fmt.Printf("%U\n", []rune(after))
}
[U+3042 U+000A U+3044 U+000D U+3046 U+000D U+000A U+3048]
[U+3042 U+000A U+3044 U+000A U+3046 U+000A U+3048]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment