Go MatchString()

1 개요[ | ]

Go MatchString()
Go regexp.MatchString()
  • 패턴이 문자열과 일치하는지를 검사하는 함수
  • 문자열이 정규표현식에 부합하는지 여부를 반환하는 함수
Go
CPU
-1.0s
MEM
-0M
-1.0s
Copy
package main

import (
	"fmt"
	"regexp"
)

func main() {
	// 백슬래시를 인용하지 않으려면 raw 문자열을 사용하자.
	match, _ := regexp.MatchString(`p([a-z]+)ch`, "peach")
	fmt.Println(match) // true
}
true
Go
Copy
package main

import (
	"fmt"
	"regexp"
)

func main() {
	// 보통 최초에 한번 표현식을 컴파일한다.
	r, _ := regexp.Compile(`p([a-z]+)ch`)
	fmt.Println(r.MatchString("peach")) // true
}
Loading
Go
Copy
package main

import (
	"fmt"
	"regexp"
)

func main() {
	var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

	fmt.Println(validID.MatchString("adam[23]")) // true
	fmt.Println(validID.MatchString("eve[7]"))   // true
	fmt.Println(validID.MatchString("Job[48]"))  // false
	fmt.Println(validID.MatchString("snakey"))   // false
}
Loading
Go
Copy
package main

import (
	"fmt"
	"regexp"
)

func main() {
	var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

	fmt.Println(validID.MatchString("adam[23]")) // true
	fmt.Println(validID.MatchString("eve[7]"))   // true
	fmt.Println(validID.MatchString("Job[48]"))  // false
	fmt.Println(validID.MatchString("snakey"))   // false
}
Loading
Go
Copy
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(gopher){2}`)

	fmt.Println(re.MatchString("gophergopher"))       // true
	fmt.Println(re.MatchString("gophergophergopher")) // true
	fmt.Println(re.MatchString("gopher"))             // false
}
Loading

2 같이 보기[ | ]

3 참고[ | ]