Maverick
Maverick

Reputation: 2022

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.

Upvotes: 1

Views: 82

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

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.

Upvotes: 1

Mark Shevchenko
Mark Shevchenko

Reputation: 8197

Simplest regex to match with 1-12 is (1[0-2]?)|[2-9].

It matches with 13 cause 1[0-2]? matches with 1, but it doesn't matter in full regex (1[0-2]?)|[2-9]\/\d\d\d\d.

Upvotes: 0

anubhava
anubhava

Reputation: 784958

You can use this regex:

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

RegEx Demo

Upvotes: 1

vks
vks

Reputation: 67968

So i have to select digits between 1-12

For that you can use regex

(?:0?[1-9]|1[0-2])

See demo.

https://www.regex101.com/r/fJ6cR4/23

Upvotes: 1

Related Questions