Home > Back-end >  Alphanumeric serial with hyphen not working using Go's regex
Alphanumeric serial with hyphen not working using Go's regex

Time:10-18

My ideal regex would return true if the serial matched something like below.

A12T-4GH7-QPL9-3N4M

Here is what I tried.

package main

import "fmt"
import "regexp"

func main() {
    a := "A12T-A12T"
    re := regexp.MustCompile("[a-zA-Z0-9]-[a-zA-Z0-9]")
    fmt.Println(re.MatchString(a))

    b := "A12T-A12T-"
    re2 := regexp.MustCompile("[a-zA-Z0-9]-[a-zA-Z0-9]-")
    fmt.Println(re2.MatchString(b))
}

Observe how the variable a is true but as soon as b is called it returns false with the extra hyphen.

My question is, how do I add multiple hyphens in-between alphanumeric characters for this ideal sequence A12T-4GH7-QPL9-3N4M

CodePudding user response:

You need to use

regexp.MustCompile("^[a-zA-Z0-9] (?:-[a-zA-Z0-9] )*$")

The pattern matches

  • ^ - start of string
  • [a-zA-Z0-9] - one or more alphanumeric
  • (?:-[a-zA-Z0-9] )* - zero or more occurrences of a hyphen and then one or more alphanumeric chars
  • $ - end of string.

See the regex demo.

CodePudding user response:

The regexp you've used matches only 3 (4 in the second example) characters.

If you want to match a set of characters separated by hyphens, you should try a regexp like ([a-zA-Z0-9] -) [a-zA-Z0-9]

which translates to code as:

package main

import "fmt"
import "regexp"

func main() {
    a := "A12T-4GH7-QPL9-3N4M"
    re := regexp.MustCompile("([a-zA-Z0-9] -) [a-zA-Z0-9] ")
    fmt.Println(re.MatchString(a))
}

https://play.golang.org/p/dMoIOaeUHBa

  • Related