Find Matches with Regex in Go
When working with Go, you may encounter the need to match specific patterns within strings using regular expressions. Here's how to accomplish this using the regexp package:
Question:
How can I find all matches for a specified regular expression within a given string and return them as an array?
Example:
Consider the string: "{city}, {state} {zip}". The goal is to return an array containing all substrings enclosed by curly braces.
Initial Attempt:
Using the regexp package, you may have tried the following code:
r := regexp.MustCompile("/({[^}]*})/") matches := r.FindAllString("{city}, {state} {zip}", -1)
However, this code returns an empty slice, indicating that no matches were found.
Solution:
To fix this issue, consider the following steps:
For All Matches:
r := regexp.MustCompile(`{[^{}]*}`) matches := r.FindAllString("{city}, {state} {zip}", -1) fmt.Println(matches) // Prints: [{city}, {state}, {zip}]
For Captured Parts Only:
r := regexp.MustCompile(`{([^{}]*)}`) matches := r.FindAllStringSubmatch("{city}, {state} {zip}", -1) for _, v := range matches { fmt.Println(v[1]) // Prints: city, state, zip }
The above is the detailed content of How to Efficiently Find All Regex Matches in a Go String?. For more information, please follow other related articles on the PHP Chinese website!