I am trying to validate email addresses. And want to reject semi-colons in the input string. My tests were passing though. I swapped around the position of the underscore char in my regex pattern, and the test then failed.
package main
import (
"log"
"regexp"
)
func main() {
testString := "a;"
m, e := regexp.MatchString("^[a-zA-Z0-9.-_]+$", testString)
if e != nil {
log.Println(e.Error())
}
log.Println("tested:", testString, m) // true
// underscore is no longer the last char in pattern
m, e = regexp.MatchString("^[a-zA-Z0-9._-]+$", testString)
if e != nil {
log.Println(e.Error())
}
log.Println("tested:", testString, m) // false
}
In the first example, you are actually listing all of the punctuations from . to _ with “-” and your “;” condition in your test string evaluates to true because of that.
On the other hand, in your second example, you are not listing all punctuations and giving the condition only for dot, underscore or dash. So your semicolon is not matching and evaluating to false.