Skip to content
Related Articles

Related Articles

Improve Article

Golang | Extracting a 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 extract a regular expression from the given string with the help of the FindString() method. This method returns a string which holds the text of the leftmost match in a given string of the regular expression. If there is no match found, then this method returns an empty string, but it will also return an empty string if the regular expression successfully matches an empty string. 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) FindString(str string) string

Example 1:




// Go program to illustrate how to find
// the regexp from the given string
  
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding regexp from the given string
    // Using FindString() method
    m := regexp.MustCompile(`geek`)
  
    fmt.Println(m.FindString("GeeksgeeksGeeks, geeks"))
    fmt.Println(m.FindString("Hello! geeksForGEEKs"))
    fmt.Println(m.FindString("I like Go language"))
    fmt.Println(m.FindString("Hello, Welcome"))
  
}

Output:

geek
geek

Example 2:




// Go program to illustrate how to find
// the regexp from the given string
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Finding the regexp from the given string
    // Using Find() method
    m := regexp.MustCompile(`like.?`)
    res := m.FindString("I45, like345, Go-234 langu34age")
  
    // Finding the index value of 
    // regexp in the given string
    // UsingFindStringIndex() method
    r := m.FindStringIndex("I45, like345, Go-234 langu34age")
      
    fmt.Printf("Found: %s with index value: %d", res, r)
}

Output:

Found: like3 with index value: [5 10]



My Personal Notes arrow_drop_up
Recommended Articles
Page :