Golang | Extracting all the Regular Expression from the String

A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.
In Go regexp, you are allowed to find all the regular expression in the given string with the help of FindAllString() method. This method returns a slice of all the successive matches of the specified regular expression, as defined by the ‘All’ description in the package comment. Or this method will return nil if not match found and here count indicates the number of substrings the returned slice. This method is defined under the regexp package, so for accessing this method you need to import the regexp package in your program.

Syntax:

func (re *Regexp) FindAllString(str string, m int) []string

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to find
// all the regexp from the given slice
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding all regexp from 
    // the given string
    // Using FindAllString () method
    m := regexp.MustCompile(`geeks.`)
  
    fmt.Println(m.FindAllString("GeeksgeeksGeeks, geeks", -1))
    fmt.Println(m.FindAllString("Hello! geeksForGEEKsgeeks-geeks", 2))
    fmt.Println(m.FindAllString("I like Go language", 0))
    fmt.Println(m.FindAllString("Hello, Welcome", 1))
  
}

chevron_right


Output:

[geeksG]
[geeksF geeks-]
[]
[]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to find
// all the regexp from the given slice
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding the number from 
    // the given string
    // Using FindAllStrings() method
    s := "I45, like345, Go-234 langu34age"
  
    m := regexp.MustCompile(`[-]?\d[\d]*[\]?[\d{2}]*`)
    res := m.FindAllString(s, 2)
    for _, ele := range res {
        fmt.Println("Number:", ele)
    }
}

chevron_right


Output:

Number: 45
Number: 345


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.