Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression checking for two consecutive spaces?

I am trying to validate the following condition:
Characters allowed, Max length of 5: A-Z, 0-9, space and ('-
and this is what I have got so far:

/^[a-zA-Z,\d,\-,\(,\']{1,5}$/;

How do I check for two consecutive spaces?

like image 429
user1127051 Avatar asked Jan 23 '12 03:01

user1127051


3 Answers

Probably match it again against /\s\s/.

like image 66
sblom Avatar answered Oct 19 '22 09:10

sblom


You can check for two consecutive spaces by using the repetition regex. i.e If you want to match a regex which repeats say between 1 to 12 times, you can give,

regex{1, 12}

Similarly, if u want to match a space which repeats just two times and not more or less than that, you can give

\s{2}

Remember that this is a general way of checking the repeat patterns. The numbers in curly braces will always try to see the number of repetitions which the previous regex has.

cheers!

like image 37
Ricketyship Avatar answered Oct 19 '22 10:10

Ricketyship


So my assumption, you want to allow space characters, but want to disallow consecutive spaces (you don't make it clear in which way you want to check for them).

You could achieve this with a negative lookahead.

^(?!.*  )[a-zA-Z\d(' -]{1,5}$

Just add the space to the character class and use the zero width negative lookahead assertion to ensure that the expression will fail, if there are two consecutive space characters.

See it here on Regexr

Btw. I removed the commas from your character class most of the escaping and moved for that reason the hyphen to the end of the class.

like image 24
stema Avatar answered Oct 19 '22 09:10

stema