A Regular Expression (or RegEx) is a special sequence of characters that defines a search pattern that is used for matching specific text. In Golang, there’s a built-in package for regular expressions, called the regexp package which contains all list of actions like filtering, replacing, validating, or extracting. It uses the RE2 syntax standards. The MatchString() function reports whether the string passed as a parameter contains any match of the regular expression pattern.
Syntax:
func MatchString(pattern string, s string)
Returns: matched bool, err error
Example:
package main
import (
"fmt"
"regexp"
)
func main() {
str := "geeksforgeeks"
match1, err := regexp.MatchString( "geeks" , str)
fmt.Println( "Match: " , match1, " Error: " , err)
str2 := "ComputerScience"
match2, err := regexp.MatchString( "geeks" , str2)
fmt.Println( "Match: " , match2, "Error: " , err)
match3, err := regexp.MatchString( "geek(s" , str2)
fmt.Println( "Match: " , match3, "Error: " , err)
}
|
Output:
Match: true Error: <nil>
Match: false Error: <nil>
Match: false Error: error parsing regexp: missing closing ): `geek(s`
To store complicated regular expressions for reuse later, Compile() method parses a regular expression and returns a Regexp object if successful which can be used to match the text. Prototype of the function is:
func Compile(expr string) (*Regexp, error)
There are other various methods provided in the regexp package to match strings as shown:
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
re, _ := regexp.Compile( "geek" )
str := "I love geeksforgeeks"
match := re.FindStringIndex(str)
fmt.Println(match)
str2 := "I love computer science"
match2 := re.FindStringIndex(str2)
fmt.Println(match2)
re2, _ := regexp.Compile( "[0-9]+-v.*g" )
match3 := re2.FindString( "20024-vani_gupta" )
fmt.Println(match3)
match4 := re.FindAllStringSubmatchIndex( "I'am a geek at" +
" geeksforgeeks" , -1)
fmt.Println(match4)
re3, _ := regexp.Compile( " " )
match5 := re3.ReplaceAllString( "All I do" +
" is code everytime." , "+" )
fmt.Println(match5)
re4, _ := regexp.Compile( "[aeiou]+" )
match6 := re4.ReplaceAllStringFunc( "All I do" +
" is code everytime." , strings.ToUpper)
fmt.Println(match6)
}
|
Output:
[7 11]
[]
20024-vani_g
[[7 11] [15 19] [23 27]]
All+I+do+is+code+everytime.
All I dO Is cOdE EvErytImE.
Last Updated :
19 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...