Friday, March 29, 2019

Using Regular Expressions in Go

Go language provides package regexp for making use of regular expressions in Go programming. The syntax of the regular expressions is almost identical to that supported by other languages like Perl, Python etc.

Let's start with the basics. We will try to use regexp package to find out if a given text contains any alphanumeric words. By alphanumeric words, we mean any word that is comprised of letters or numerals.

To do this, we will compile a regexp object out of a regular expression. Then we use this regexp object on input strings to check if they contain any alphanumeric words or not, and if they do, we print each one of them.

Here is a program for doing this.

package main
import (
"fmt"
"regexp"
)
func printMatches (r *regexp.Regexp, s string ) {
// Use the FindAllString() function to find all
// the resulting matching strings.
// FindAllString() will return nil if it doesn't
// find any matches.
// If it does it will return a slice containing
// all the matches
matches := r.FindAllString(s,-1)
if matches != nil {
// If matches were found, traverse the slice
// and print them one by one
fmt.Println("Here are the matches found in ", s)
for _, match := range matches {
fmt.Println(match)
}
} else {
// If no matches found, output an error message
// and return
fmt.Println("No Alpha Numeric Words found in", s)
}
}
func main() {
// Compile a regular expression that matches
// alpahnumeric words. We get a regular expression
// object in return.
alphaNumericWords := regexp.MustCompile(`\w+`)
// Pass the test string and the object to our function
// that checks if regular expression matches or not.
// and print the results
input1 := "You gotta be kidding me, Mr 23"
printMatches(alphaNumericWords,input1);
input2 := "...... !!!!!"
printMatches(alphaNumericWords,input2);
}
view raw RegExp1.go hosted with ❤ by GitHub



No comments:

Post a Comment