0

I'm checking for StringPatterns. This is the RegEx:

Regex regEx = new Regex("(\\d{4}/\\d{1})");

Text examples look like this: 1234/5,1234/6,1234/8. Everything works fine till there is a String like "1234/89", and the result of the match is still true. What am I missing? I also had this RegEx:

Regex regEx = new Regex("(\\d{4}/\\d{1}\\W)");

With the problem, that this one had the examples I mentioned as a non-match and therefor marked them false.

James K. Lowden
  • 7,574
  • 1
  • 16
  • 31
P. Edge
  • 105
  • 1
  • 7
  • Why not use /d+ instead of specifically specifying {4} digits and {1} digit. The last nine of 89 is being dropped because you are only looking for one digit instead of two. – jdweng Jul 23 '16 at 15:51
  • Tip: Use @ before your string to not have to escape the "\"'s, which makes the entire thing more confusing. – iuliu.net Jul 23 '16 at 15:52

2 Answers2

4

You're missing that fact that your regex should always match the whole string, but in your case, even the part of string is matched. Use start / end anchors:

^(\\d{4}/\\d{1})$
nicael
  • 18,550
  • 13
  • 57
  • 90
  • 1
    Thank you! This is a typical example for not beeing able to see the forest for the trees and embarrassing. – P. Edge Jul 23 '16 at 15:54
-2
static void Code () {

    Regex regEx = new Regex(@"(\d{4}/\d{1,2})");

    foreach (string input in new string [] {
        "1234/5", "1234/6", "1234/8", "1234/89"
    })
        Console.WriteLine (regEx.IsMatch (input));

    /*
        True
        True
        True
        True
    */

}
marsouf
  • 1,107
  • 8
  • 15