Home > Net >  Unexpected Go regex behavior
Unexpected Go regex behavior

Time:08-24

I have a Go regular expression which is supposed to match a string that starts with a plus-sign followed by 2 to 15 digits:

`\ \d{2,15}`

Testing it like this gives confirms that a string I expect it to match, actually matches:

regexp.MustCompile(`\ \d{2,15}`).MatchString(" 4790") // true, as expected

But when I add a hyphen to the string, I expect it to NOT match. However, it still says it matches. Why?

regexp.MustCompile(`\ \d{2,15}`).MatchString(" 47-90") // true, should be false?

CodePudding user response:

As the stdlib doc says (italics mine):

MatchString reports whether the string s contains any match of the regular expression pattern.

So if you want the exact match, make the boundaries explicit:

regexp.MustCompile(`^\ \d{2,15}$`).MatchString(" 47-90")
  • Related