Go by Example: Regular Expressions

Go provides a package called “regexp” for working with regular expressions. Regular expressions are a pattern-matching language that can be used to match and manipulate strings.

Here’s a basic example that demonstrates how to use regular expressions in Go:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "hello, world 123456"
	re := regexp.MustCompile("[0-9]+")

	matches := re.FindAllString(text, -1)
	for _, match := range matches {
		fmt.Println(match)
	}
}

In this example, a variable text is defined with a string to be matched. The regexp.MustCompile function is used to compile a regular expression pattern into a regular expression object, which is stored in the re variable.

The re.FindAllString method is then called to find all substrings in text that match the regular expression pattern. The second argument to re.FindAllString specifies the maximum number of matches to return. A value of -1 means “find all matches”.

The matches variable will be a slice of strings, where each element is a matching substring from the text. In this example, the output will be:

123456

Note that this example demonstrates the use of a very simple regular expression pattern, [0-9]+, which matches one or more consecutive digits. Regular expressions can be much more complex and sophisticated than this simple example. The regexp package provides a rich set of functions and options for working with regular expressions in Go.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *