C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Important: With byte slices, we must convert them back to strings before printing them. This can be annoying.
Golang program that uses Find
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))
}
Output
205
String: We operate directly on strings with FindAllString the results are in a slice of strings, so we can print them with no conversion.
Golang program that uses FindAllString
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])
}
}
Output
123
124
125