Go: Find first substring matching a regexp

Use the FindString method to find the text of the first match. If there is no match, the return value is an empty string.

re := regexp.MustCompile(`foo.?`)
fmt.Printf("%q\n", re.FindString("seafood fool")) // "food"
fmt.Printf("%q\n", re.FindString("meat"))         // ""

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!