views:

744

answers:

5

How can I create a regex expression which will match only letters and numbers, and one space between each word?

Good Examples:

Amazing

Hello Beautiful World

I am 13 years old

Bad Examples:

Hello  world

I am 13 years      old.

I    am   Chuck Norris
A: 

This would match a word

'[a-zA-Z0-9]+\ ?'
Arkaitz Jimenez
Great, now make that handle a line :-)
paxdiablo
No, it would match *some* words. Only those containing the (ascii) ranges a-z and A-Z. The word `café` would not be matched. It would also match strings that consist solely of digits like `01012009`, something I wouldn't call a word.
Bart Kiers
+1  A: 
([a-zA-Z0-9]+ ?)+?
brysseldorf
And a space at the start of the line is handled how? :-)
paxdiablo
+2  A: 

Most regex implementations support named character classes:

^[[:alnum:]]+( [[:alnum:]]+)*$

You could be clever though a little less clear and simplify this to:

^([[:alnum:]]+ ?)*$

FYI, the second one allows a spurious space character at the end of the string. If you don't want that stick with the first regex.

Also as other posters said, if [[:alnum:]] doesn't work for you then you can use [A-Za-z0-9] instead.

John Kugelman
I'll give you a vote if you add " ?" at the start to handle a single space at the start of the line/string (and the ^$ anchor points). Everything else seems good.
paxdiablo
It dosen't seems to work (I need it in ASP RegExp)
TTT
Sorry, just saw your edit. It's working great the following regex: ^([A-Za-z0-9]+ ?)*$Thank you so much!
TTT
A: 
Heinrich Filter
A: 
^[a-zA-Z]+([\s][a-zA-Z]+)*$
mirezus