Home
Go
regexp.Find Examples
This page was last reviewed on Sep 23, 2024.
Dot Net Perls
Find. With regexp we are often trying to find strings within a larger string. We use patterns (passed to MustCompile) to determine which values match.
To use Find, we must have byte slices. This is inconvenient in some programs. We can use a method like FindAllString instead, to operate directly on strings.
regexp.MatchString
regexp.Split
regexp.ReplaceAllString
Find example. Here we use Find. We try to find a 3-digit sequence that begins with the value 2. The Find method returns the leftmost matching sequence as a byte slice.
Important With byte slices, we must convert them back to strings before printing them. This can be annoying.
package main import ( "fmt" "regexp" ) func main() { // Match 3-digit values starting with 2. re := regexp.MustCompile("2\\d\\d") // Use find to get leftmost match. result := re.Find([]byte("123 124 125 205 211")) // Convert back to string and print it. fmt.Println(string(result)) }
205
FindAllString. This func finds multiple matches of a pattern within a string. It returns the values in a slice—we can loop over it with a for-loop.
for
Info We operate directly on strings with FindAllString. The results are in a slice of strings, so we can print them with no conversion.
package main import ( "fmt" "regexp" ) func main() { // Match 3-char values starting with digit 1. re := regexp.MustCompile("1..") // Find and loop over all matching strings. results := re.FindAllString("123 124 125 200 211", -1) for i := range(results) { fmt.Println(results[i]) } }
123 124 125
With Find methods, we perform a search within the source string—the entire string is not matched as in MatchString(). We can test matches in a for-loop after the method call.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 23, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.