tags:

views:

56

answers:

4

I need a regular expression that matches a 15 character string as follows:

  • Characters 1-6 should match '100702'
  • Characters 7-8 should match '25' or '26'
  • Characters 9-15 should match any digit (0-9) but must contain a digit.

This is for .NET

Thank you.

A: 

Here is a good article on using a tool to write Regex's http://www.codeproject.com/KB/dotnet/regextutorial.aspx and here is a good resource for looking up the matching characters and formats http://www.zytrax.com/tech/web/regex.htm. If you need help after this, please let me know, and I will help you along.

CaffeineZombie
+1  A: 

Here is one that would work for .NET, following your description:

^1007022(5|6)\d{1,7}$

See this reference.

Oded
Characters 9 to 15 are 7 digits... ;) And all 15 digits are always required (as I understand the question).
Daniel Brückner
@Daniel Brückner - thanks ;)
Oded
+3  A: 

This should do the job.

^100702(25|26)[0-9]{7}$
Daniel Brückner
+4  A: 

This is basically what your description says:

100702(?:25|26)\d{7}

Can also be written:

1007022[56]\d{7}


You might want to put ^ at the start and $ at the end if you need to match it entirely (although certain functions will do this automatically).

Peter Boughton
+1, but add `^$` anchors.
Richard Szalay
Was editing that in as you commented. :)
Peter Boughton
Just a thought - I would always prefer `(25|26)` over `2[56]` or `2(5|6)` because it clearly expresses the requirements. This is always good and especially for our unreadable regular friends.
Daniel Brückner
I would suggest that you want {1,7} not just {7} at the end there; not sure whether you agree given the ambiguity of "9-15 should match any digit (0-9) but must contain a digit."
Altreus
Because of the first line of the question: "[...]that matches a 15 character string as follows" I tend to believe `{7}` is correct.
Daniel Brückner
Daniel, yes I wrote the (?:25|26) first for that reason - the `?:` tells it not to capture the group (since that was neither asked nor implied necessary). I guess based on the accepted answer that the `{1,7}` range was what was wanted, despite the unclear description.
Peter Boughton