0

I am new to learning Regex and I am struggling with this basic issue. I want to make sure a string is in a format like: 2000/2001 or 2010/2011.

I tried something like: ^[2000-2900]./.[2000-2900]$ but I know this is wrong!

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
Mike91
  • 520
  • 2
  • 9
  • 25
  • [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – Simon Mar 14 '13 at 17:08
  • You're struggling - What have you tried? What platform are you using? Did you forgot to escape the slash? – Bergi Mar 14 '13 at 17:08
  • You must tag the programming language you're using, otherwise there's no way of telling what regex patterns will work for you. – zzzzBov Mar 14 '13 at 17:10
  • possible duplicate of [Regular Expression: Numeric range](http://stackoverflow.com/questions/1377926/regular-expression-numeric-range); read http://www.regular-expressions.info/numericranges.html – Bergi Mar 14 '13 at 17:11
  • 1
    If you're going to build a regular expression you should be using a test-driven approach, define a set of input values that should pass, and, more importantly, a set of input values that should fail. – zzzzBov Mar 14 '13 at 17:12
  • 1
    Btw, here's a good tool for learning regex: http://regexpal.com/ (check out the quick reference menu on top right) – Simon Mar 14 '13 at 17:22

2 Answers2

6

This would be the very basic:

^\d{4}\/\d{4}$

From the beginning of the string, check if it has 4 digits followed by a "/" (escaped with "\") and another 4 digits to the end of the string.

Simon
  • 7,182
  • 2
  • 26
  • 42
1

If you searching for where the entire string must match then:

^\d{4}/\d{4}$

If you are searching for a sub string of a larger string then:

\d{4}/\d{4}

And if you using in C# then remember to wrap it up in a verbatim string like so:

@"^\d{4}/\d{4}$"
@"\d{4}/\d{4}"

I noticed that others are escaping the forward slash but I don't think is necessary but doesn't do any harm if you do.

Dave Sexton
  • 10,768
  • 3
  • 42
  • 56