概要
よく忘れるので、ついでにメモメモ。
文字列末尾の改行コードを除去したいときがたまにあるのですが、Goの場合は正規表現を使うよりも strings パッケージの関数を使った方が楽なときが多いです。
以下のような感じ。Unix系(LinuxとかmacOSとか) なら CR の処理はいらないですが、windowsも考慮に入れると必要)
func chop(s string) string { s = strings.TrimRight(s, "\n") if strings.HasSuffix(s, "\r") { s = strings.TrimRight(s, "\r") } return s }
サンプル
package strs import ( "strings" "github.com/devlights/gomy/output" ) // ChopNewLine -- 文字列末尾の改行を削除するサンプルです func ChopNewLine() error { var ( withLF = "helloworld\n" withCRLF = "helloworld\r\n" withoutNewLine = "helloworld" ) output.Stdoutl("[has newline? (withLF) ]", strings.HasSuffix(withLF, "\n")) output.Stdoutl("[has newline? (withCRLF) ]", strings.HasSuffix(withCRLF, "\n")) output.Stdoutl("[has newline? (withoutNewLine) ]", strings.HasSuffix(withoutNewLine, "\n")) // 末尾の改行を削除 chopLF := chop(withLF) output.Stdoutl("[has newline? (chopped)(LF) ]", strings.HasSuffix(chopLF, "\n")) output.Stdoutl("[equal? (chopped==withoutNewLine)]", chopLF == withoutNewLine) chopCRLF := chop(withCRLF) output.Stdoutl("[has newline? (chopped)(CRLF) ]", strings.HasSuffix(chopCRLF, "\n")) output.Stdoutl("[equal? (chopped==withoutNewLine)]", chopCRLF == withoutNewLine) output.StdoutHr() output.Stdoutl("[LF ]", []byte(withLF)) output.Stdoutl("[CRLF ]", []byte(withCRLF)) output.Stdoutl("[chopLF ]", []byte(chopLF)) output.Stdoutl("[chopCRLF]", []byte(chopCRLF)) output.Stdoutl("[without ]", []byte(withoutNewLine)) return nil } func chop(s string) string { s = strings.TrimRight(s, "\n") if strings.HasSuffix(s, "\r") { s = strings.TrimRight(s, "\r") } return s }
実行すると以下のようになります。
[Name] "string_chop_newline" [has newline? (withLF) ] true [has newline? (withCRLF) ] true [has newline? (withoutNewLine) ] false [has newline? (chopped)(LF) ] false [equal? (chopped==withoutNewLine)] true [has newline? (chopped)(CRLF) ] false [equal? (chopped==withoutNewLine)] true -------------------------------------------------- [LF ] [104 101 108 108 111 119 111 114 108 100 10] [CRLF ] [104 101 108 108 111 119 111 114 108 100 13 10] [chopLF ] [104 101 108 108 111 119 111 114 108 100] [chopCRLF] [104 101 108 108 111 119 111 114 108 100] [without ] [104 101 108 108 111 119 111 114 108 100] [Elapsed] 0s
おすすめ書籍
自分が読んだGo関連の本で、いい本って感じたものです。
- 作者:Katherine Cox-Buday
- 発売日: 2018/10/26
- メディア: 単行本(ソフトカバー)
- 作者:松尾 愛賀
- 発売日: 2016/04/15
- メディア: 単行本(ソフトカバー)
プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES)
- 作者:Alan A.A. Donovan,Brian W. Kernighan
- 発売日: 2016/06/20
- メディア: 単行本(ソフトカバー)
過去の記事については、以下のページからご参照下さい。
- いろいろ備忘録日記まとめ
サンプルコードは、以下の場所で公開しています。
- いろいろ備忘録日記サンプルソース置き場