Ehsan Ahmed Farooqi
Ehsan Ahmed Farooqi

Reputation: 9

Underscore as well to regular expression

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

Answers (5)

Hooopo
Hooopo

Reputation: 1400

You may try this code:

^[a-zA-Z0-9]*[a-zA-Z0-9_-]+[a-zA-Z0-9]*$

Upvotes: 0

John Dewey
John Dewey

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

Sufian Latif
Sufian Latif

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

Andrew Clark
Andrew Clark

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

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

I'd rewrite it as:

^[a-zA-Z0-9]+([-_]*[a-zA-Z0-9]+)*$

Upvotes: 0

Related Questions