Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a single space total not just a single space using regular expressions

Tags:

regex

Here is what I currently have, this will match alphanumerical characters and space:

^[a-z0-9\s]+$

What I would like to do is to ensure that there will only be a match if there is no more than one (1) space. The above will match "This is a test", but I would only want it to match if the input is "This isatest", or "T hisisatest". As soon as there is more than one space total it will no longer match.

Ideally it would also not match if the space is leading or trailing, but that's just icing.

EDIT: The idea is that this will be used to verify account names upon account creation. The account name may only contain a Latin letter, a number, and a single space. However, it could be all letters or all numbers, the space is not required. This is definitely about space and not whitespace.

like image 839
Reality Extractor Avatar asked May 28 '11 09:05

Reality Extractor


People also ask

How do you match a space in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.

What regular expression would you use to match a single character?

Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.

Does regex match dot space?

Does regex match dot space? Yes, the dot regex matches whitespace characters when using Python's re module.


1 Answers

Will allow atmost one space in between.

^[a-zA-Z0-9]+\s?[a-zA-Z0-9]+$

Will allow exactly one space in between

^[a-zA-Z0-9]+\s[a-zA-Z0-9]+$

EDIT1:

Above solutions does not accept single character strings.

The below solutions also matches single character strings

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

like image 120
phoxis Avatar answered Oct 10 '22 16:10

phoxis