views:

296

answers:

7

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?

+10  A: 

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}$
VoteyDisciple
No understanding why you have an extra ^...
Kelsey
@Kelsey: [^\s] is the same as [\S]
R. Bemrose
@Kelsey: The ^ at the beginning of the string means it only matches the beginning of the string, and the $ at the end means it only matches the end of the string.
yodaj007
Ah but one takes more typing to produce the same results:) i++; or i = i + 1; :P
Kelsey
@yodaj007 I know taht the ^ and $ do, see my answer below where I explained it all in detail. I just thought the use of two ^ was not needed.
Kelsey
The two ^ have completely different meanings. The one at the beginning binds to the beginning of the string, as in your example; the one inside the character class negates that class. As R. Bemrose points out above, [^\s] is the same as [\S]. I used the former only because that's what was in Matt's original code.
VoteyDisciple
A: 

Something like /^[^\s]{4}$/

xximjasonxx
A: 

try out txt2re.com works for me.

+7  A: 

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

Kelsey
+1 for a great explanation!
p.campbell
+1  A: 
\S{4}

will match 4 non-whitespace characters. If you are using c# regex, I highly recommend Expresso.

Rob Elliott
Problem is because you have excluded the beginning and ending bits, it will also match text that is greater than 4 characters. He wants exactly 4 characters.
Kelsey
A: 

Alright, edited out my less-good answer, since a better version was covered above, but figured I'd leave this part of my answer, since some might find it useful:

When testing C# regular expressions, I've found this site to be really helpful, as it allows you to quickly and easily test the expressions against various sample inputs, and with different RegEx flags set.

Sterno
A: 

In Java:

[^\s]{4,4}
Megadix