Home >Backend Development >Golang >How to Extract All Substrings Enclosed in Curly Braces Using Go's Regex?
Finding All String Matches Using Regex in Go
When working with strings in Go, it's often necessary to find specific patterns or substrings. Regular expressions offer a powerful way to match and manipulate text. One common task is to find all matches of a particular pattern and store them in a slice or array.
Problem Statement:
Given a string containing curly braces enclosing substrings, the goal is to extract all the substrings between the braces and return them as an array. For example, given the string:
{city}, {state} {zip}
We need to return an array containing:
Solution:
To accomplish this, we can utilize Go's regexp package. However, there are a few key points to note when defining the regular expression:
Here's the updated Go code:
package main import ( "fmt" "regexp" ) func main() { str := "{city}, {state} {zip}" // Define the regular expression pattern r := regexp.MustCompile(`{[^{}]*}`) // Find all matches matches := r.FindAllString(str, -1) // Print the matches for _, match := range matches { fmt.Println(match) } }
Regex Breakdown:
Output:
{city} {state}
The above is the detailed content of How to Extract All Substrings Enclosed in Curly Braces Using Go's Regex?. For more information, please follow other related articles on the PHP Chinese website!