tags:

views:

318

answers:

6

What is the regular exp for a text that can't contain any special characters except space?

+2  A: 

[\w\s]*

\w will match [A-Za-z0-9] and the \s will match whitespaces.

[\w ]* should match what you want.

Alan Haggai Alavi
\s matches all whitespace characters which Prajeesh specifically wants to exclude.
Josh
I have edited accordingly. Thank you, Josh.
Alan Haggai Alavi
A: 

If you just want alphabets and spaces then you can use: @"[A-Za-z\s]+" to match at least one character or space. You could also use @"[A-Za-z ]+" instead without explicitly denoting the space.

Otherwise please clarify.

Ahmad Mageed
A: 

In C#, I'd believe it's ^(\w|\s)*$

Anzurio
A character class would be better: ^[\w\s]*$, but that depends on whether you count things like tabs as being spaces.
Chas. Owens
+4  A: 

Assuming "special characters" means anything that's not a letter or digit, and "space" means the space character (ASCII 32):

^[A-Za-z0-9 ]+$
Alan Moore
+2  A: 

You need @"^[A-Za-z0-9 ]+$". The \s character class matches things other than space (such as tab) and you since you want to match sure that no part of the string has other characters you should anchor it with ^ and $.

Chas. Owens
Could you please tell me what is the use of anchor in a regx?
Sauron
Different RegEx parsers utilize different anchors, but basically ^ anchors the match to the beginning of the string, while $ anchors to the end of the string. So [a] used on the string 'aaaaa' would yield five matches, while ^[a] would produce only one.
Josh
Here: http://www.regular-expressions.info/anchors.html
Alan Moore
+2  A: 

Because Prajeesh only wants to match spaces, \s will not suffice as it matches all whitespace characters including line breaks and tabs.

A character set that should universally work across all RegEx parsers is:

[a-zA-Z0-9\0x0020]

Further control depends on your needs. Word boundaries, multi-line support, etc... I would recommend visiting Regex Library which also has some links to various tutorials on how Regular Expression Parsing works.

Josh