LoginSignup
1
1

More than 3 years have passed since last update.

【Golang】標準パッケージ regex

Last updated at Posted at 2020-06-09

【Golang】標準パッケージ regex

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main
//regex 正規表現
//URLなどによって処理を分岐させたい場合など、判定してプログラムを書くなど

import (
    "fmt"
    "regexp"
)

func main() {
    //MatchString
    //正規表現のフォーマットに沿った文字列か確認し、True/Falseを返す
    //aからはじまってeで終わる。間はa-zが1つ以上。数字も使う場合はa-z0-9にする。
    match, _ := regexp.MatchString("a([a-z]+)e", "apple")
    fmt.Println(match)
    //>>true



    //MustCompile
    //上記と同じ。何度も使う場合は、最初に定義を宣言して使った方がいい
    r := regexp.MustCompile("a([a-z]+)e")
    ms := r.MatchString("apple")
    fmt.Println(ms)
    //>>true



    //FindString
    //MustCompileの中でURIを正規表現で定義し、FindStringで、そのルールに収まっているか確認をするという使い方もできる。
    //^ $ 先頭 終わりが数字アルファベット 空白を持たない
    r2 := regexp.MustCompile("^/(index|detail|create)/([a-zA-Z0-9]+)$")
    ///index/testに、マッチする文字列を取得する
    fs := r2.FindString("/index/test")
    fmt.Println(fs)
    //>>/index/test



    //FindStringSubmatch
    //格納されるデータはスライスで入っているので、一つ一つ取り出すことも可能。
    //indexだけ取り出したいなど
    //スライスで取得される
    fss := r2.FindStringSubmatch("/index/test")
    fmt.Println(fss, fss[0], fss[1], fss[2], len(fss))
    //>>[/index/test index test] /index/test index test 3
    //スライスで取り出せる


    //改行がある場合を検知する場合^ $ではなく、\A \zを使う
    //セキュリティ上望ましい。
    r3:= regexp.MustCompile(`\A/(index|detail|create)/([a-zA-Z0-9]+)\z`)
    fs3 := r3.FindString("/index/test")
    fmt.Println(fs3)//len(fs3)
}
1
1
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
1