Golang 查找字符串中的正则表达式的索引
正则表达式是一个定义搜索模式的字符序列。Go语言支持正则表达式。
在 Go regexp 中,你可以在 FindStringIndex() 方法的帮助下找到指定正则表达式在给定字符串中的最左边的索引值。该方法返回一个两元素的整数片,该整数片定义了正则表达式在给定字符串中最左边的匹配位置,匹配结果如str[loc[0]:loc[1]] 。或者,如果没有找到匹配,它将返回 nil。这个方法是在regexp包下定义的,所以要访问这个方法,你需要在你的程序中导入regexp包。
语法
func (re *Regexp) FindStringIndex(str string) (loc []int)
例1 :
// Go program to illustrate how to find the
// index value of the regexp in the given string
package main
import (
"fmt"
"regexp"
)
// Main function
func main() {
// Finding index regexp
// from the given string
// Using FindStringIndex() method
m := regexp.MustCompile(`ee`)
fmt.Println(m.FindStringIndex("GeeksgeeksGeeks, geeks"))
fmt.Println(m.FindStringIndex("Hello! geeksForGEEKs"))
fmt.Println(m.FindStringIndex("I like Go language"))
fmt.Println(m.FindStringIndex("Hello, Welcome"))
}
输出
[1 3]
[8 10]
[]
[]
例2 :
// Go program to illustrate how to find the index
// value of the regexp in 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(`345`)
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: 345 with index value: [9 12]
极客教程