Go: Find the location of a regexp substring match

Use the FindStringIndex method to find loc, the location of the first match, in a string s. The match is at s[loc[0]:loc[1]]. A return value of nil indicates no match.

re := regexp.MustCompile(`ab?`)
fmt.Println(re.FindStringIndex("tablett"))    // [1 3]
fmt.Println(re.FindStringIndex("foo") == nil) // true

There are several more search functions available in the regexp package. The strings All, String, Submatch, and Index can be combined to form the methods:

Find(All)?(String)?(Submatch)?(Index)?

Comments

Be the first to comment!