Skip to content
Related Articles

Related Articles

Improve Article

Golang | Extracting all the Regular Expression from the String

  • Last Updated : 05 Sep, 2019

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:




// 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))
  
}

Output:

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

Example 2:




// 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)
    }
}

Output:

Number: 45
Number: 345



My Personal Notes arrow_drop_up
Recommended Articles
Page :