Menu Close

MatchReader function in regexp package in go

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

Understanding the MatchReader Function:

The MatchReader function in regexp package in go returns a boolean indicating whether a text from an io.Reader matches a particular regex pattern.


func MatchReader(pattern string, r io.Reader) (matched bool, err error)

The MatchReader function takes two arguments:

  1. pattern: a string representing the regular expression pattern you wish to match.
  2. r: an object satisfying the io.Reader interface from which the text will be read.

The function returns two values:

  1. matched: a boolean value which is true if the regular expression matches the text and false otherwise.
  2. err: an error object which will be non-nil if an error occurred during execution, such as if the regular expression pattern is invalid.


package main

import (





func main() {

	pattern := "[a-z]+"

	reader := strings.NewReader("Hello, World!")

	matched, err := regexp.MatchReader(pattern, reader)

	if err != nil {

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



	if matched {

		fmt.Println("Match found!")

	} else {

		fmt.Println("No match found.")



In this code, we’re checking whether the string “Hello, World!” contains one or more lowercase letters. strings.NewReader is used to create an io.Reader from the string.

We then call regexp.MatchReader with the pattern and the reader. If there’s an error during execution, an error message is printed and the program returns. If there’s no error, it checks whether a match was found and prints a corresponding message.

On running this program, the output will be “Match found!“, since the string “Hello, World!” does contain lowercase letters.


Match found!

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


Posted in golang, packages, regexp

Leave a Reply

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