» Quick Introduction to Go » 2. Intermediate » 2.3 Regular Expressions

Regular Expressions

The regexp package provides support for regular expressions.

The syntax of the regular expressions accepted is the same general syntax used by Perl, Python, and other languages. More precisely, it is the syntax accepted by RE2 and described at https://github.com/google/re2/wiki/Syntax.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// Creating a simple regular expression to match an email address
	emailRegex := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)

	emails := []string{
		"lite.rank@example.com",
		"invalid-email",
		"another.email@domain",
	}

	for _, email := range emails {
		if emailRegex.MatchString(email) {
			fmt.Printf("%s is a valid email address\n", email)
		} else {
			fmt.Printf("%s is NOT a valid email address\n", email)
		}
	}
}

Code Challenge

Write a Go program that validates a list of phone numbers based on the following criteria:

  1. The phone number must consist of 10 digits.
  2. It can start with an optional '+' sign, followed by the country code (1 to 4 digits), and then the 10-digit phone number.
Loading...
> code result goes here
Prev
Next