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
How to wait for Goroutines to Finish Execution?
How to check lowercase characters in a string in Golang?
Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time
How to convert Boolean Type to String in Go?
Split URL and Get Parameters from URL
Example: Split, Join, and Equal from BYTES Package