tags:

views:

1920

answers:

2

The string can have Alphabets [a-zA-Z] It can have numbers [0-9] but min 0 and max 2 spaces are allowed And for special characters max 1 hyphen, and max 1 comma

+5  A: 

There are several ways to do that. Here is one using look-ahead assertions:

^(?=[^ ]* ?[^ ]*(?: [^ ]*)?$)(?=[^-]*-?[^-]*$)(?=[^,]*,?[^,]*$)[a-zA-Z0-9 ,-]*$
Gumbo
My eyes! (+1 for effort!)
Andre Miller
+1  A: 

I'd like to note that this can be achieved easily without regular expressions, in a much more maintainable way (what would happen if next month you want 3 dashes and 5 digits - how would that regex look?).
Consider:

string s = "abcd2,6  ";
bool valid =
    (
        (s.Count(' '.Equals) <= 2) &&
        (s.Count(','.Equals) <= 1) &&
        (s.Count('-'.Equals) <= 1) &&
        (s.Count(char.IsDigit) <= 2)
    );

(even if you don't have linq this could be done easily)

If you also want to check for English letters you can match against @"^[a-zA-Z0-9 ,-]*$" - this will check the characters but won't count them (I took a small bit from Gumbo's regex).

Kobi