5

In go there is the function MatchString which can be used to match a string with a regex, however, the function returns true if a substring that matches the regex is found.

Is there a way/similar function that returns true only when the whole of the string is matched (e.g. if I have [0-9]{2} and my string is 213, the return value should be false). ? or should this be done from the regex string itself ?

George H
  • 412
  • 3
  • 6
  • 12

1 Answers1

7

Try this:

^[0-9]{2}$

Explanation

GO CODE:

package main

import (
    "regexp"
    "fmt"
)

func main() {
    var re = regexp.MustCompile(`(?m)^[0-9]{2}$`)
    var str = `213`

    for i, match := range re.FindAllString(str, -1) {
        fmt.Println(match, "found at index", i)
    }
}

Run the code here

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43