TechDo
TechDo

Reputation: 18629

Regular expression to allow space in c# not working when multiple space comes

I have a regular expression to check the data entered in a text box. It allows only alpha numeric plus hyphen (-), underscore (_) and white spaces. It works fine for singe values. But if I enter multiple spaces or underscores, it fails. Below is my expression:

Regex.IsMatch(Text, "^[A-Za-z0-9-_ ]*$")

Please suggest if there is any other way to do this or the expression can be changed.

This expression is used in a multi-line text box, so line breaks have to be included as well.

Upvotes: 0

Views: 4988

Answers (4)

user2268788
user2268788

Reputation: 266

You need to add an option to allow it to work multi-line. It won't be the multiple spaces or underscores breaking it, but rather line breaks.

Change your regex to the following, and it should work...

Regex.IsMatch(Text, "^[A-Za-z0-9-_ ]*$",RegexOptions.Multiline)

As others suggested, it's also better to use \s instead of a literal space. Add the IgnoreCase option to make regex simpler. Finally escape your hyphen for clarity.

vb.net

Regex.IsMatch(Text, "^[a-z0-9\-_\s]*$",RegexOptions.Multiline or RegexOptions.IgnoreCase)

C#

Regex.IsMatch(Text, @"^[a-z0-9\-_\s]*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

Upvotes: 1

hwnd
hwnd

Reputation: 70722

Replace the space character with \s to allow any whitespace character.

Regex.IsMatch(Text, @"^[a-zA-Z0-9\s_-]*$")

String text = @"foo-
bar  baz _____________     
quz_";

Regex.IsMatch(text, "^[a-zA-Z0-9-_ ]*$");    // False
Regex.IsMatch(text, @"^[a-zA-Z0-9\s_-]*$");  // True

Upvotes: 2

shree.pat18
shree.pat18

Reputation: 21757

Try this:

Regex.IsMatch(Text, "^[A-Za-z0-9-_\\s]*$")

My understanding is that \s matches whitespaces including CRLF, which would cover OP's use case of a multiline textbox. Therefore, I believe it would be better to replace " " with "\s".

Upvotes: 3

SimonGA
SimonGA

Reputation: 94

You should actually change the Regular Expression into using defined tags for whitespace characters (\s) and alphanumeric values (\w).

\s will take care of spaces, tabs and line breaks (which you need for the multi line input)
\w will take care of alphanumeric and underscore.
The only other thing you then need is hyphen, which is simply just inputting a hyphen.

This makes your final Regex look like this:

^[\w\s-]*$

And the C# could would be:

Regex.IsMatch(Text, @"^[\w\s-]*$")

A good place to test your regular expressions and get help would be a page like RegExr: http://www.regexr.com/

Upvotes: 1

Related Questions