使用Go的正则表达式时,带有连字符的字母数字序列无法正常工作。

huangapple go评论75阅读模式
英文:

Alphanumeric serial with hyphen not working using Go's regex

问题

我的理想正则表达式将在序列匹配以下内容时返回true。

A12T-4GH7-QPL9-3N4M

以下是我尝试过的内容。

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))
}

请注意,变量a为true,但一旦调用变量b,它会返回false,因为有额外的连字符。

我的问题是,如何在字母数字字符之间添加多个连字符以匹配理想序列A12T-4GH7-QPL9-3N4M。

英文:

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

答案1

得分: 2

你使用的正则表达式只匹配了3个字符(第二个示例中是4个字符)。

如果你想匹配由连字符分隔的一组字符,你可以尝试使用类似于([a-zA-Z0-9]+-)+[a-zA-Z0-9]+的正则表达式。

对应的代码如下:

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

英文:

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

答案2

得分: 2

你需要使用以下正则表达式进行匹配:

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

该模式匹配:

  • ^ - 字符串的开头
  • [a-zA-Z0-9]+ - 一个或多个字母数字字符
  • (?:-[a-zA-Z0-9]+)* - 零个或多个连字符和一个或多个字母数字字符的组合
  • $ - 字符串的结尾。

请参考正则表达式演示

英文:

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.

huangapple
  • 本文由 发表于 2021年10月18日 04:40:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/69608420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定