Search code examples
c#regexlookbehindnegative-lookbehind

Regex issue i am stuck with


I have to write a regex for matching a pattern 1-6/2011. In this case, digits before the / can not be greater than 12. So I have to select digits between 1-12.

I have written a regex:

^[1-9][0-2]?\s*[-−—]\s*[1-9][0-2]?\s*/\s*2[01][0-9][0-9]$

However, here I am getting 20-6/2014 also as a match.

I tried with a negative look-behind:

^[1-9](?<![2-9])[0-2]?\s*[-−—]\s*[1-9](?<![2-9])[0-2]?\s*/\s*2[01][0-9][0-9]$

Here, single digits are not getting identified.


Solution

  • You can use the following update of your regex:

    ^(?:0?[1-9]|1[0-2])\s*[-−—]\s*(?:0?[1-9]|1[0-2])\s*/\s*\s*2[01][0-9]{2}$
    

    See demo

    It will not match 12-30/2014, 12-31/2014, 12-32/2014, 13-31/2014, 20-6/2014.

    It will match 1-6/2011 and 02-12/2014.

    C#:

    var lines = "1-6/2011\r\n02-12/2014\r\n12-30/2014\r\n12-31/2014\r\n12-32/2014\r\n13-31/2014\r\n20-6/2014";
    var finds = Regex.Matches(lines, @"^(?:0?[1-9]|1[0-2])\s*[-−—]\s*(?:0?[1-9]|1[0-2])\s*/\s*\s*2[01][0-9]{2}\r?$", RegexOptions.Multiline);
    

    Mind that \r? is only necessary in case we test with Multiline mode on. You can remove it when checking separate values.