Menu Close

Match function in regexp package in go

In this tutorial, We are going to learn about Match function in regexp package in go with example and in details.


Understanding the Match Function:

The Match function in regexp package in go is utilized to check whether a regular expression matches a particular pattern in the specified string or byte slice.


Syntax:

func Match(pattern string, b []byte) (matched bool, err error)


Here’s how it is typically used:

matched, err := regexp.Match(pattern, content)

In this case, pattern is a string representation of the regular expression you wish to match and content is the byte slice against which the pattern is matched.

The function returns two values:

  1. matched: A boolean value that signifies whether the pattern was found in the content or not. It returns true if a match is found, false otherwise.
  2. err: It holds an error object which will be non-nil in case there is an error during execution, such as if the regular expression pattern is invalid.


Example:

package main


import (

	"fmt"

	"regexp"

)


func main() {

	pattern := "[a-z]+"

	content := []byte("Hello, World!")


	matched, err := regexp.Match(pattern, content)

	if err != nil {

		fmt.Println("Error occurred during matching:", err)

		return

	}


	if matched {

		fmt.Println("Match found!")

	} else {

		fmt.Println("No match found.")

	}

}

In this code, we first import the necessary packages. The main package is regexp, which provides the Match function. The pattern we’re trying to match is “[a-z]+”, which matches one or more lowercase letters. The content is the byte slice representation of the string “Hello, World!”.

We then call the Match function with the pattern and the content. If there’s an error during the execution, it prints an error message and returns from the program. If there’s no error, it checks whether a match was found and prints a corresponding message.


Output:

Match found!

To learn more about golang, You can refer given below link:

https://techieindoor.com/regexp-package-in-go/

References:

https://golang.org/pkg/

Posted in golang, packages, regexp

Leave a Reply

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