Matt
Matt

Reputation: 5595

How can I create a regular expression that requires 4 characters and no spaces?

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?

Upvotes: 5

Views: 32090

Answers (7)

Ali Umair
Ali Umair

Reputation: 1424

This might be helpful if someone is looking for 4 characters only, no numbers,spaces or special characters

var regexp = /^([a-zA-Z]){4}$/;
console.log(regexp);
var isValid = regexp.test('abcd');
console.log("Valid: " + isValid);

Upvotes: 0

Kelsey
Kelsey

Reputation: 47726

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

Upvotes: 11

Dimitri De Franciscis
Dimitri De Franciscis

Reputation: 1032

In Java:

[^\s]{4,4}

Upvotes: 1

user94154
user94154

Reputation: 16564

try out txt2re.com works for me.

Upvotes: 0

Rob Elliott
Rob Elliott

Reputation: 2008

\S{4}

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

Upvotes: 1

xximjasonxx
xximjasonxx

Reputation: 1212

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

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37803

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}$

Upvotes: 19

Related Questions