LoginSignup
1
0

More than 1 year has passed since last update.

【Go】正規表現で文字列から数字だけを抽出する方法

Posted at

実装例

import文に"regexp"を追加
toInt64()の引数にチェックしたい文字列を入れることで数字が抜き出されてint64型が返ってくる

func toInt64(strVal string) int64 {
    rex := regexp.MustCompile("[0-9]+")
    strVal = rex.FindString(strVal)
    intVal, err := strconv.ParseInt(strVal, 10, 64)
    if err != nil {
        fmt.Println(err)
    }
    return intVal
}

解説

rex := regexp.MustCompile("[0-9]+")

MustCompileは正規表現が間違っていたらエラーを出力する。
ここで"[0-9]+"の部分が数字だけを抜き出すための表現。

strVal = rex.FindString(strVal)

strVal(string型)の中に入っている数字だけを抜き出して文字列としてstrValに再代入している。

もしstrVal"str123and456"のようになっていて、全ての数字をリストで抜き出したいときにはFindAllStringを使う。

複数抜き出したい場合

submatchall := rex.FindAllString(str1, -1)
for _, element := range submatchall {
    fmt.Println(element)
}

Output

123
456

参考

1
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
1
0