英文:
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-]+$
答案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_-]*
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论