tags:

views:

48

answers:

3

I am still learning RegEx so I need some help on this one.

Rules are as below:

  • Min/Max Length of string: 1-5
  • String has to be a whole word
  • String can contain: A-Z and/or a-z and/or 0-9 or combination of both only (e.g. _ - . * are not allowed)

Examples:

12345 – allowed
Os342 – allowed
2O3d3 – allowed
3sdfds dsfsdf – not allowed
Sdfdf.sdfdf –now allowed

Thanks.

+3  A: 

What about:

string input = "12345";
bool match = Regex.IsMatch(input, "^[a-z0-9]{1,5}$", RegexOptions.IgnoreCase);
Rubens Farias
Without ^ and $, the regexp tester he gave me matched "12345" of "123456"; apparently that should be rejected though.
Carl Smotricz
you're right carl, fixed
Rubens Farias
And you were right about those other chars. I deleted my answer, thanks.
Carl Smotricz
@Rubens, I am just wondering why didn't you include A-Z?
Jeffrey C
@Jeffrey: I used RegexOptions.IgnoreCase, so will not differ a-z from A-Z (as OP said is working with C#). But you can remove it and to add A-Z if you wish
Rubens Farias
+3  A: 

How about

^[A-Za-z0-9]{1,5}$
S.Mark
+3  A: 
^[a-zA-Z0-9]{1,5}$
  • [a-zA-Z0-9] specifies the ranges allowed
  • ^ specifies start of string
  • $ specifies end of string
  • {1,5} indicates minimum and maximum number of characters for the range
Darko Z
You want to do `1,5` to catch strings shorter than 5 chars too, I think.
Carl Smotricz