Reputation: 3183
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.
Upvotes: 1
Views: 7326
Reputation: 174874
Keep it simple. You could use a negative lookahead at the start.
^(?![_-])[\w-]+$
Upvotes: 2
Reputation: 85224
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])?$
Upvotes: 5
Reputation: 465
You need to split up your expression, and match the first character separately, and do the following:
[A-Za-Z][A-Za-z0-9_-]*
Upvotes: 0