0

I need a regular expression for a string like this:

ex. 1234-1234-12345

where the first two numbers must be between 01-18 and the whole string must be 15 characters long

example: 0511-xxxx-xxxxx.

I tried using [RegularExpression(@"^[0-9]{1,18}$", ErrorMessage = "Invalid Id.")]

but it doesnt work, it even gives me an error that says ',' is missing.


Lets make it even easier, a numeric string 13 character long where the first two digits must be between 01-18.

Ex. 1234567890123

(I would prefer the first format but this one work too).


I don't know how to use Regex so if someone can kindly give me a link to somewhere I can learn I would very much appreciate it.

And, most importantly, if there is a better way to get around this without using Regex I would appreciate it as well.


Apparently, my request is a little unclear. What I want it that the first two digits (XXxx-xxxx-xxxxx) be 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18.

Eduardo
  • 23
  • 1
  • 6

1 Answers1

1

Your "first two numbers" is a little unclear, but how about:

var pattern = @"(0\d|1[0-8])\d\d-\d{4}-\d{5}";

If you want to match the whole string and not just find the substring, you need

var pattern = @"^(0\d|1[0-8])\d\d-\d{4}-\d{5}$";

If you didn't have the groups separated by hyphens, use:

var pattern = @"^(0\d|1[0-8])\d{11}$";

You can use it like

Regex.IsMatch(aString, pattern)
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • NVM. Thanks! I was a fool and I didnt see yours was great. Now, can you explain it to me? Specially this part ^(0\d|1[0-8]). How would it be if I only wanted numbers? No '-'? – Eduardo Jun 16 '17 at 02:25
  • I am not sure what you mean by "only wanted numbers"? If you removed the `-` then `[08]` means a `1` digit followed by a `0` digit or an `8` digit is acceptable - so you would be accepting `10` or `18`. See here for an explanation of the expression: https://regex101.com/r/kFObNJ/1 - let me know if you have further questions. – NetMage Jun 16 '17 at 17:49
  • NM - I see what you mean. I added another pattern for just numbers. – NetMage Jun 16 '17 at 17:51
  • the [0-8] part is fine. What I mean is that I want to know how it would be if the expression is meant to be purely numeric: 0144786598775 or 1812131456789. And my program can't accept expresions like this: 00xxxxxxxxxxx that start with (00). The starting numbers must be from (01 to 18) – Eduardo Jun 16 '17 at 17:52
  • thanks! It works great. But what if my expresions can't accept "00xxx..." The starting numbers must be from (01 to 18) – Eduardo Jun 16 '17 at 17:54
  • Then change the leading portion to `^(0[1-9]|`. – NetMage Jun 16 '17 at 17:56