Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this regex allow spaces c#

Tags:

c#

regex

I have a phone number field with the following regex:

[RegularExpression(@"^[0-9]{10,10}$")]

This checks input is exactly 10 numeric characters, how should I change this regex to allow spaces to make all the following examples validate

1234567890
12 34567890
123 456 7890

cheers!

like image 881
MikeW Avatar asked Jul 19 '12 03:07

MikeW


3 Answers

This works:

^(?:\s*\d\s*){10,10}$

Explanation:

^ - start line
(?: - start noncapturing group
\s* - any spaces
\d - a digit
\s* - any spaces
) - end noncapturing group
{10,10} - repeat exactly 10 times
$ - end line

This way of constructing this regex is also fairly extensible in case you will have to ignore any other characters.

like image 54
Eugene Ryabtsev Avatar answered Oct 19 '22 11:10

Eugene Ryabtsev


Use this:

^([\s]*\d){10}\s*$

I cheated :) I just modified this regex here:

Regular expression to count number of commas in a string

I tested. It works fine for me.

like image 20
Jason Antic Avatar answered Oct 19 '22 12:10

Jason Antic


Depending on your problem, you might consider using a Match Evaluator delegate, as described in http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

That would make short work of the issue of counting digits and/or spaces

like image 25
Dominic Cronin Avatar answered Oct 19 '22 12:10

Dominic Cronin