-1

my RegularExpression-skills are in need of improvement. So maybe somebody could help me to get back on track.

Background: I have a TextBox where the user can enter a year/week-Combination instead of entering the date. I'm converting that on serverside to a date instance(last day of that week). Now i have to validate this with a RegularExpressionValidator.

Format: An exemplary format could be 10w32 for year 2010 and calendar-week 32. The digit w is case-insentive. The weeknumber should be between 1 and 53. Other valid examples:

99w02  -> 1999 week 2
2W53   -> 2002 week 53
2001w1 -> 2001 week 1

Thank you in advance.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939

1 Answers1

2

How about

\d{1,4}[wW](\d|([0-4]\d)|(5[0123]))

? (Suitably escaped, of course).

Explanation:

  • 1-4 digits
  • w or W
  • Either a single digit...
  • ... or two digits whether the first is 0-4 and the second is any digit
  • ... or 5 followed by 0, 1, 2 or 3

It's possible that some of the grouping in the alternation construct is unnecessary - this may work too:

\d{1,4}[wW](\d|[0-4]\d|5[0123])

... test it to see.

This is completely untested, mind you... unit tests are your friend, along with careful scrutiny.

Use ^ at the start and $ at the end to force the regex to match the whole string, e.g.

^\d{1,4}[wW](\d|[0-4]\d|5[0123])$
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • First, thank you. But the test fails for f.e. `5w16` and all other valid formats. Checked on http://www.nvcc.edu/home/drodgers/ceu/resources/test_regexp.asp and with an ASP.Net-RegularExpressionValidator. – Tim Schmelter Jan 21 '11 at 11:25
  • @Tim: Fixed - the `{1-4}` should have been `{1,4}` – Jon Skeet Jan 21 '11 at 11:35