以字母数字和连字符开头,后面是下划线的正则表达式。

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

Regex for starting with alphanumeric and hyphen, underscore later in string

问题

我正在尝试在Golang中编写一个正则表达式,用于匹配以字母数字开头并可以在后面带有下划线或连字符的字符串,但不能以连字符或下划线开头。

以下是我能想到的正则表达式,但它会匹配任何位置的字母数字、连字符和下划线:

[A-Za-z0-9_-]

因此,sea-food这样的字符串会匹配,或者seafood或sea_food,但不会匹配-seafood或_seafood。

英文:

I'm trying to write a regexp in golang that matches strings that start as alphanumeric and can have an underscore or hyphen after, but not starting with a hyphen or underscore.

Here is what I could come up with, but this matches alphanumeric and hyphen underscore anywhere

[A-Za-z0-9_-]

So something like sea-food would match or seafood or sea_food, but not -seafood nor _seafood.

答案1

得分: 5

你需要使用 ^ 表示字符串的开头,使用 $ 表示字符串的结尾,然后使用两个字符类:

^[A-Za-z0-9][A-Za-z0-9_-]*$

如果还要禁止字符串末尾的连字符和下划线,可以尝试:

^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$

英文:

You need to use a ^ to indicate the start of the string and $ for the end, and then use two character classes:

^[A-Za-z0-9][A-Za-z0-9_-]*$

To disallow hyphens and underscores at the end of the string as well try:

^[A-Za-z0-9]([A-Za-z0-9_-]*[A-Za-z0-9])?$

答案2

得分: 2

保持简单。你可以在开头使用负向预查。

^(?![_-])[\w-]+$

演示

英文:

Keep it simple. You could use a negative lookahead at the start.

^(?![_-])[\w-]+$

DEMO

答案3

得分: 0

你需要将表达式分割开,并单独匹配第一个字符,然后执行以下操作:

[A-Za-Z][A-Za-z0-9_-]*

英文:

You need to split up your expression, and match the first character separately, and do the following:

[A-Za-Z][A-Za-z0-9_-]*

huangapple
  • 本文由 发表于 2014年10月15日 03:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/26368618.html
匿名

发表评论

匿名网友

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

确定