Go Regular Expressions - Simple Matching and Extracting of Data

Go like most modern languages has tremendous regular expressions. The problem is that I really don't like needing to search a long reference page for the things that I use most often. I searched my code and 90% of the time I am:

  1. Testing to see if a string matches a regular expression.
  2. Matching a regular expression and replacing all occurrences with a new string.
  3. Parsing a simple string and extracting some information out of it.

I put together these examples so that I could refer to them myself. This shows the usage case that I am most interested in.

Match a string with a regular

Example (re00.go):

package main

import (
	"fmt"
	"regexp"
)

func main() {
	var fn = "abc.md"
	var re1 = regexp.MustCompile("\\.md$")
	res := re1.FindAllStringSubmatch(fn, -1)
	fmt.Printf("fn=%s\n", res) // Print out the matches, 0 length array if no match.
	if len(res) == 0 {
		fmt.Printf("Did not match.\n")
	} else {
		fmt.Printf("Match Found.\n")
	}
}
 

Match a string with a regular expression and replace

Example (re01.go):

package main

import (
	"fmt"
	"regexp"
)

func main() {
	var fn = "abc.md"
	var re1 = regexp.MustCompile("\\.md$")
	fn = re1.ReplaceAllString(fn, "")
	fmt.Printf("fn=%s\n", fn) // Print out results
}
 

If a match, then extract some data

Example (re02.go):

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile("([a-zA-Z_][a-zA-Z_0-9]*)=(.*)")   // Create the RegEx
	fmt.Printf("%q\n", re.FindAllStringSubmatch("abc=123", -1)) // Print out results
	x := re.FindAllStringSubmatch("abc", -1)
	fmt.Printf("%q %d\n", x, len(x)) // Print out len of results
	if len(x) == 0 {
		fmt.Printf("no match\n")
	}
	fmt.Printf(" the name before the = is [%s]\n", x[0][1])
	fmt.Printf(" the value after the = is [%s]\n", x[0][2])
}
 

One thing that I keep in mind is that regular expressions are far more expensive than just a string match. If I am just looking for one string inside another I can use a non-regular expression match.

Example (nore1.go):

package main

import (
	"fmt"
	"strings"
)

func main() {
	if strings.Contains("my text", "tex") {
		fmt.Printf("Found 'tex' in 'my text'\n")
	} else {
		fmt.Printf("Not Found!  No 'tex' in 'my text'\n")
	}
}
 


•       •       •       •       •       •

Summary: # of Words: 319
Author: Philip J. Schlump
Published On: 2013-11-07

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens