Golang 从字符串中提取正则表达式
正则表达式是一个定义搜索模式的字符序列。Go语言支持正则表达式。
在 Go regexp 中,你可以借助 FindString() 方法从给定的字符串中提取正则表达式,进行解析、过滤、验证和提取有意义的信息。该方法返回一个字符串,该字符串持有正则表达式给定字符串中最左边的匹配文本。如果没有找到匹配项,那么这个方法就会返回一个空字符串,但是如果正则表达式成功匹配了一个空字符串,它也会返回一个空字符串。这个方法是在 regexp 包下定义的,所以为了访问这个方法,你需要在你的程序中导入 regexp 包。
语法
func (re *Regexp) FindString(str string) string
例1 :
// Go program to illustrate how to find
// the regexp from the given string
package main
import (
"fmt"
"regexp"
)
// Main function
func main() {
// Finding regexp from the given string
// Using FindString() method
m := regexp.MustCompile(`geek`)
fmt.Println(m.FindString("GeeksgeeksGeeks, geeks"))
fmt.Println(m.FindString("Hello! geeksForGEEKs"))
fmt.Println(m.FindString("I like Go language"))
fmt.Println(m.FindString("Hello, Welcome"))
}
输出
geek
geek
例2 :
// Go program to illustrate how to find
// the regexp from the given string
package main
import (
"fmt"
"regexp"
)
// Main function
func main() {
// Finding the regexp from the given string
// Using Find() method
m := regexp.MustCompile(`like.?`)
res := m.FindString("I45, like345, Go-234 langu34age")
// Finding the index value of
// regexp in the given string
// UsingFindStringIndex() method
r := m.FindStringIndex("I45, like345, Go-234 langu34age")
fmt.Printf("Found: %s with index value: %d", res, r)
}
输出
Found: like3 with index value: [5 10]
极客教程