Regular expression to extract text between square brackets
Example
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
str1 := "this is a [sample] [[string]] with [SOME] special words"
re := regexp.MustCompile(`\[([^\[\]]*)\]`)
fmt.Printf("Pattern: %v\n", re.String()) // print pattern
fmt.Println("Matched:", re.MatchString(str1)) // true
fmt.Println("\nText between square brackets:")
submatchall := re.FindAllString(str1, -1)
for _, element := range submatchall {
element = strings.Trim(element, "[")
element = strings.Trim(element, "]")
fmt.Println(element)
}
}
Output
Pattern: \[([^\[\]]*)\]
Matched: true
Text between square brackets:
sample
string
SOME
Most Helpful This Week
Regular expression to extract numbers from a string in Golang
Replace any non-alphanumeric character sequences with a dash using Regex
Regular expression to validate the date format in "dd/mm/yyyy"
How to replace emoji characters in string using regex in Golang?
Regex to extract image name from HTML in Golang
How to extract text from between html tag using Regular Expressions in Golang?