Golang 寻找Slice中的正则表达式的索引

Golang 寻找Slice中的正则表达式的索引

正则表达式是一个定义搜索模式的字符序列。Go语言支持正则表达式。

Go regexp 中,你可以在 FindIndex() 方法的帮助下,在给定的字节片中找到指定正则表达式的最左边的索引值。该方法返回一个两元素的整数片,该整数片定义了正则表达式的给定片中最左边的匹配位置,匹配结果如s[loc[0]:loc[1]]。或者,如果没有找到匹配,它将返回 nil。这个方法是在regexp包下定义的,所以要访问这个方法,你需要在你的程序中导入regexp包。

语法

func (re *Regexp) FindIndex(s []byte) (loc []int)

例1 :

// Go program to illustrate how to find the index
// value of the regexp in the given slice
  
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding the index value of regexp 
    // from the given slice of bytes
    // Using FindIndex() method
    m := regexp.MustCompile(`ek`)
  
    fmt.Println(m.FindIndex([]byte(`GeeksgeeksGeeks, geeks`)))
    fmt.Println(m.FindIndex([]byte(`Hello! geeksForGEEKs`)))
    fmt.Println(m.FindIndex([]byte(`I like Go language`)))
    fmt.Println(m.FindIndex([]byte(`Hello, Welcome`)))
  
}

输出

[2 4]
[9 11]
[]
[]

例2 :

// Go program to illustrate how to find the
// index value of the regexp in the given slice
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding regexp from
    // the given slice
    // Using Find() method
    m := regexp.MustCompile(`45`)
    res := m.Find([]byte(`I45, like345, Go-234 langu34age`))
  
    if res == nil {
        fmt.Println("Nil found")
    } else {
  
        // Finding the index value of
        // the regexp from the given slice
        // Using FindIndex() method
        r := m.FindIndex([]byte(`I45, like345, Go-234 langu34age`))
        fmt.Printf("Found: %q with index value: %d", res, r)
    }
}

输出

Found: "45" with index value: [1 3]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程