I know there are plenty of questions on here asking why their regex fails, but I can't see any specifically for Go/Golang.
I have an ID type which is a string with some methods tacked on: type ID string
, and this function which is supposed to return a bool if the ID is valid.
My criteria for validity are:
- 20 characters long.
- Any upper case letter A-Z.
- Any digit 0-9.
So my regular expression, which I've tested on a few different online tools is /[A-Z0-9]{20}/
But every time I run my validate function it returns false, regardless of input. Specifically, the regexp.MatchString()
function is returning false and nil.
Below is my validation function, match is ALWAYS false, even when I change the regex to /.{20}/
which is supposed to match 20 of anything.
func (this ID) validate() bool {
regexString := "/[A-Z0-9]{" + strconv.Itoa(MAX_ID_LENGTH) + "}/"
fmt.Println(regexString)
thisStr := this.ToString()
fmt.Println(thisStr)
charCount := utf8.RuneCountInString(thisStr)
fmt.Println(charCount)
thisStr = strings.ToUpper(thisStr)
fmt.Println(thisStr)
match, err := regexp.MatchString(regexString, thisStr)
fmt.Println(match, err)
//Check string length is correct and matches regex.
if charCount != MAX_ID_LENGTH || !match {
return false
} else {
return true
}
}
Is it to do with the way I'm using the function? I'm stumped.
Note: the .ToUpper() function is there because when my IDs are generated they are only produced with upper case letters and 0-9, but I want "abc" to be treated as "ABC" if typed manually at a later date.