Golang : Extract pattern using regular expression

In the below example, all texts inside square brackets in extracted using FindAllString function.
func (re *Regexp) FindAllString (s string, n int) [ ] string returns a slice of all successive matching texts based on the regular expression.
Integer n signifies the number of matches. n = -1 would return all matches.


Go ( Golang ) : Extracting all text from square brackets

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {

    var text = "Extract from square brackets [abc ... zzz] and [algo go] from this [line]."

    exp := regexp.MustCompile(`\[.*?\]`)

    // Matches would contain a slice of all successive matching text
    // based on the regular expression.
    matches := exp.FindAllString(text, -1) 
    fmt.Println("All matches : " + strings.Join(matches," "))

    for _, matching_text := range matches {
        fmt.Println (matching_text)
    }   
    fmt.Println("First 3 matches : " + strings.Join(exp.FindAllString(text, 3), " "))
    fmt.Println("First 2 matches : " + strings.Join(exp.FindAllString(text, 2), " "))
    fmt.Println("First 1 matches : " + strings.Join(exp.FindAllString(text, 1), " "))
    fmt.Println("First 0 matches : " + strings.Join(exp.FindAllString(text, 0), " "))
}

Output

All matches : [abc ... zzz] [algo go] [line]
[abc ... zzz]
[algo go]
[line]
First 3 matches : [abc ... zzz] [algo go] [line]
First 2 matches : [abc ... zzz] [algo go]
First 1 matches : [abc ... zzz]
First 0 matches : 


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.