0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GO言語:備忘録(学習記録)①

Last updated at Posted at 2025-02-01

はじめに

・こちらはGO言語の個人学習の備忘録となっております。
 参考にした情報が古いものであったり、誤った情報であることもあるかもしれませんので
そういった場合は、ご教示いただけると幸いです。

GO言語 文字列操作

 Go言語では正規表現「regexp」パッケージを使用するよりも、「strings」パッケージを使用する方が良いとのこと

理由:「regexp」パッケージのパフォーマンスが非常に悪いため

そのため、文字列操作をしたい場合は、「regexp」ではなく「strings」パッケージが良いらしい

※2019年発刊の書籍にて学習
※go version:1.12

「strings」パッケージ

よく使うパターン
// 対象の文字列が指定した文字列で始まるか
HasPrefix(s, prefix string) bool

// 対象の文字列が指定した文字列で終わるか
HasSuffix(s, suffix string) bool

//対象の文字列が指定した文字列を含むか
Contains(s, substr string) bool

//文字列を空白区切りで分割
Fields(s string) []string

//指定した文字(セパレータ)で文字列を分割
Split(s, sep string) []string

//指定した文字(セパレータ)で文字列を分割(最大nの長さで戻す)
SplitN(s, sep string, n int) []string

//対象の文字列の前後の空白を除去
TrimSpace(s string) string

//対象の文字列の前後からcutsetに含まれる文字を除去
Trim(s string, cutset string) string

//対象の文字列を置換する
Replace(s, old, new string, n int) string

どうしても正規表現を使用したい場合は、可能な限り初期化時に生成する。
その際、正規表現パターンの生成には「regexp.MustCompile」を使用する。
また、正規表現の文字列は「" "」ではなく「' '」を使用することで、
余計なエスケープを省き可読性を上げる意識を持つこと。

「regexp」パッケージ その1

どうしても正規表現を使う場合
// regexp.MustComile
var worReg = regexp.MustCompile('¥w+')

※Must※※※という関数の命名規則は、絶対に引数を間違う可能性がない場合に使われる。
万が一引数が間違っていた場合には、panicを発生させることが慣例となっている。
そのため、実行中の関数の中で使用してはならないということを意識して使うように。

関数の実行中に動的に正規表現を使用したい場合は、「regexp.Compile」を使用すること。

「regexp」パッケージ その2

動的に正規表現を使用したい場合
reg, err := regexp.Compile('SSS')
if err != nil {
    //エラーチェック
    }

まとめ

GO言語において文字列操作は、基本的には「strings」パッケージを使用し、
正規表現の「regexp」パッケージは最終兵器的な扱いとすること。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?