Reputation: 9
I need alpha numeric string with hyphen (-
) and underscore (_
). but -
and _
can't come alone. There must be some aplha or alpha numeric text with -
or _
.
abc- allowed
abc_abc-xyz allowed
abc896 allowed
89abc allowed
abc_ not allowed
abc- not allowed
- not allowed
_not allowed
-- not allowed
________ --- not allowed
this:
^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
expression do all the things as mentioned above but with -
I want to add _
underscore as well. And -
and _
can't come at the beginning or at the end.
Upvotes: 1
Views: 121
Reputation: 7093
This will allow a single -
and/or _
to appear in either order, but not together. Also allows straight alphanumeric:
^[a-zA-Z0-9]+[-_]{0,1}[^-_]+[-_]{0,1}[^-_]+$
This alternative also seems to work:
^[^-_]+[-_]{0,1}[^-_]+[-_]{0,1}[^-_]+$
Upvotes: 0
Reputation: 13356
You're very close to it:
^[0-9a-zA-Z]([-_]*[0-9a-zA-Z]+)*$
A better one could be:
^[0-9a-zA-Z]([-_]+[0-9a-zA-Z]|[0-9a-zA-Z]+)*$
Upvotes: 0
Reputation: 208475
Here is how I would write this:
^(?![-_])[-a-zA-Z0-9_]+(?<![-_])$
Here is a rubular: http://www.rubular.com/r/7biWZhiiVn
The ^[-a-zA-Z0-9_]+$
would be a string that only contains the characters you want. The lookahead and lookbehind make sure that the string does not begin or end with a -
or _
.
You could probably change [-a-zA-Z0-9_]
to [-\w]
since \w
is usually equivalent to [a-zA-Z0-9_]
, but Unicode options can change the meaning to include letters from other languages.
Upvotes: 1