Question

Doing the below regex match to verify whether date is in the YYYY_MM_DD Format. But the regular expression gives an error message if i have a value of 2012_07_7. Date part and month should be exactly 2 digits according to the regex pattern. Not sure why it's not working.

if ($cmdParams{RunId} !~ m/^\d{4}_\d{2}_\d{2}$/)
{
  print "Not a valid date in the format YYYY_MM_DD";
}
Was it helpful?

Solution

Your regex specifies exactly 2 digits for the day component, if you want to allow either 1 or 2 digits you should use {1,2} rather than {2}

OTHER TIPS

Well if you look at your data that you have: 2012_07_7 you can see that the day-part is not of two digits.

Obviously. Your pattern dictates that the last numeric chunk should be of two digits, whereas you are providing 1. So if you want your pattern to match this text, try something like:

if ($cmdParams{RunId} !~ m/^\d{4}_\d{2}_\d\d?$/)

My solution: ^\d{4}_(?:1[0-2]|0?[1-9])_(?:3[01]|[1-2]\d|0?[1-9])$
this pattern match: 2000_12_01 or 2001_1_1 or 2001_02_1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top