A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.
In Go regexp, you are allowed to find the leftmost index value of the specified regular expression in the given slice of bytes with the help of FindIndex() method. This method returns a two-element slice of integers which defines the location of the leftmost match in the given slice of the regular expression and the match like s[loc[0]:loc[1]]. Or it will return nil if no match found. This method is defined under the regexp package, so for accessing this method you need to import the regexp package in your program.
Syntax:
func (re *Regexp) FindIndex(s []byte) (loc []int)
Example 1:
package main
import (
"fmt"
"regexp"
)
func main() {
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`)))
}
|
Output:
[2 4]
[9 11]
[]
[]
Example 2:
package main
import (
"fmt"
"regexp"
)
func main() {
m := regexp.MustCompile(`45`)
res := m.Find([]byte(`I45, like345, Go-234 langu34age`))
if res == nil {
fmt.Println( "Nil found" )
} else {
r := m.FindIndex([]byte(`I45, like345, Go-234 langu34age`))
fmt.Printf( "Found: %q with index value: %d" , res, r)
}
}
|
Output:
Found: "45" with index value: [1 3]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Sep, 2019
Like Article
Save Article