An overview of the
In our example, we’ll use the Regexp package in Golang, which provides regular expression search capabilities golang.org/pkg/regexp/.
Before looking at the Regex itself, let’s look at some of the basic functions or methods that Go provides for regex matching.
MatchCompile function
Golang.org/pkg/regexp/…
Here is the signature of this function
func MustCompile(str string) *Regexp
Copy the code
We first compile the given regex string using the MustCompile function. If the given regex is invalid, the function will panic. When it can successfully compile the given regex, it returns an instance of the regEXP structure.
sampleRegexp := regexp.MustCompile("some_regular_expression"")
Copy the code
Matching method
Golang.org/pkg/regexp/…
Below is the signature of the method
func (re *Regexp) Match(b []byte) bool
Copy the code
We can call the Match method on the Regexp instance to Match the given pattern and the regex. Return true if the regex matches the input string, false otherwise. We need to pass the number of bytes of the input string to this method.
match := sampleRegexp.Match([]byte("some_string"))
Copy the code
Let’s look at a simple program that is a basic regex with literal or raw strings.
package main
import (
"fmt"
"regexp"
)
func main(a) {
sampleRegex := regexp.MustCompile("abc")
match := sampleRegex.Match([]byte("abc"))
fmt.Printf("For abc: %t\n", match)
match = sampleRegex.Match([]byte("1abc2"))
fmt.Printf("For 1abc2: %t\n", match)
match = sampleRegex.Match([]byte("xyz"))
fmt.Printf("For xyz: %t\n", match)
}
Copy the code
The output
For abc: true
For 1abc2: true
For xyz: false
Copy the code
In the above program, we have a simple literal string regular expression
We first check if a given regular expression is valid by calling MustCompile. We then match it with the sample string or text below
-
String “ABC “- it gives a match and prints true
-
String “1abc2″ – it provides a match and prints true. Because it contains the **” ABC “substring, it matches.
-
String “xyz” – it does not match and prints false.
Note that in the above program, it also gives a match if the given string or text contains the regex as a substring. If we want to do a full string match, then we need to use anchor characters at the beginning and end of the recombination word. The Caret anchor character will be used at the beginning and the Dollar anchor character will be used at the end.
Please refer to this article for details on full string matching
Golangbyexample.com/golang-rege…
Also, check out our Golang advanced Tutorial series at ——. Golang Advanced tutorial
The postGolang Regex: Matches The original or literal string that appears on Welcome To Golang By Example.