The homework assignment says I have to write code that validates dates in yyyy/mm/dd format. It asks that I first check the input String so that the first part, the year is exactly 4 numbers and month is between 1 and 2 (inclusive). And if it doesn't match that criteria, i throw an exception called "InvalidDateException", (I've already wrote the class for that)
So my given example is 2016/05/12
should be considered a valid date.
Looking into how Regex works, I come to the conclusion that I would need \\d+
so that java can find numbers.
Here's my code (variable date is a String, instantiated in the method that contains this code):
int yr = date.substring(0, date.indexOf("/")).length();
int mo = date.substring(date.indexOf("/")+1, date.lastIndexOf("/")).length();
if (date.matches("\\d+") && (yr == 4) && (mo <= 2 && mo >= 1)) {
//I've put code here that outputs it as a valid date
}
So then if I put 2016/05/12
, it should say that it's a valid date, however it instead goes to my error message of "InvalidDateException"
I've looked through the other regex questions on StackOverflow but I can't seem to find out why my code doesn't work.
any help is appreciated