How can I create a regular expression that requires 4 characters and no spaces?
21,658
Solution 1
Why is there an extra .
in front? That will match a separate character before your "four non-spaces" get counted.
You probably also want to bind it to the beginning and end of the string, so:
^[^\s]{4}$
Solution 2
Your making it more complicated than it needs to be and using \S
, not \s
so you don't match spaces. I think this should work for you:
^[\S]{4}$
Definition of solution:
^ - begins with
[/S] - capital 'S' means no white space
{4} - match 4 times
$ - end of string
Solution 3
\S{4}
will match 4 non-whitespace characters. If you are using c# regex, I highly recommend Expresso.
Solution 4
In Java:
[^\s]{4,4}
Author by
Matt
Updated on July 09, 2022Comments
-
Matt almost 2 years
I am trying to make the user input exactly 4 characters with no spaces... here's what I have:
.[^\s]{4}
but everything I enter says that it didn't match the regex...
Where am I going wrong?