Related Articles

Related Articles

Golang | Finding Index of the Regular Expression present in String
  • Last Updated : 05 Sep, 2019

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 string with the help of the FindStringIndex() method. This method returns a two-element slice of integers which defines the location of the leftmost match in the given string of the regular expression and the match like str[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) FindStringIndex(str string) (loc []int)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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"))
  
}

chevron_right


Output:

[1 3]
[8 10]
[]
[]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
}

chevron_right


Output:

Found: 345 with index value: [9 12]



My Personal Notes arrow_drop_up
Recommended Articles
Page :