Orion
Orion

Reputation: 27

Regular expression that accepts alphanumeric , non consecutive dash and non consecutive white space

Can anyone help me create a regular expression that accepts alphanumeric (numbers and letters only) and dashes and white spaces.

It shouldn't accept consecutive dashes and consecutive white spaces. or a dash followed by a white space and vice versa. It should always begin and end with alphanumeric characters as well.

Thank you so much. Any help would be very much appreciated. (^-^)v

'Abcde' , '324 3a-32' : valid

'-' , '324 3a - 32' , '-2323  d-', 'z- -a' : invalid

Thanks guys for all your help. v(",)\

Upvotes: 1

Views: 4807

Answers (4)

stema
stema

Reputation: 92986

An ASCII answer

^(?!.*[- ]{2})(?!^[- ])(?!.*[- ]$)[A-Za-z0-9- ]+$

See it here on Regexr

^ Matches the start of the string

$ Matches the end of the string

[A-Za-z0-9- ]+ Matches the characters you want, at least one

The negative lookaheads

(?!.*[- ]{2}) ensures that there are not - or space in a row

(?!^[- ])(?!.*[- ]$) those two ensures that it does not start and not end with these characters.

For an unicode answer you should specify the language you are using

for some you can use \p{L} See here to describe a unicode code point that has the property "letter".

Upvotes: 1

Alan Moore
Alan Moore

Reputation: 75232

Try this:

^[A-Za-z0-9]+(?:[\s-][A-Za-z0-9]+)*$

When the first [A-Za-z0-9]+ runs out of letters and digits, the [\s-] inside the group tries to match a hyphen or a whitespace character. If it succeeds, the second [A-Za-z0-9]+ tries to match some more alphanumerics. And the group gets repeated as many times as necessary.

Upvotes: 10

phlogratos
phlogratos

Reputation: 13924

Try this regular expression:

^[a-zA-Z0-9]+([ \t-]?[a-zA-Z0-9]+)*$

Upvotes: 1

Leif
Leif

Reputation: 2170

/[\da-z]+[ -]?([\da-z][ -]?)*[\da-z]/i

Upvotes: -2

Related Questions