Underscore position in regexp pattern affects result

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.

Any ideas why?

Playground link: https://play.golang.org/p/xkL9MlFja3_t

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
}
1 Like

Hello Doug,

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.

1 Like

. and - have special meanings in regular expressions. If you want literal . and - characters, then escape them with \: "^[a-zA-Z0-9\\.\\-_]+$"

Ahh, thanks. Yes, that ‘-’ as a range I didn’t realise. I tried escaping the . with a , but also didn’t realise I needed two \.

thanks both,

Of course, I have now just realised that 0-9 and A-Z should have told me all I needed to know! :slightly_smiling_face:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.