Java - slash character skew character

Can someone tell me how I use the slash escape character in Java. I know the backslash is \\, but I tried \ / and // with no luck!

Here is my code: -

public boolean checkDate(String dateToCheck) { if(dateToCheck.matches("[0-9][0-9]\ /[0-9][0-9]\ /[0-9][0-9][0-9][0-9]")) { return true; } // end if. return false; } // end method. 

Thanks in advance!

+4
source share
1 answer

You do not need to hide slashes in Java as a language or regular expressions.

Also note that blocks like this:

 if (condition) { return true; } else { return false; } 

more compactly and readily written as:

 return condition; 

So, in your case, I believe your method should look something like this:

 public boolean checkDate(String dateToCheck) { return dateToCheck.matches("[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]")); } 

Please note that this is not a good way to test for valid dates - it is probably worth trying to parse it as a date or, conversely, ideally using an API that allows you to do this without throwing an exception on failure.

Your regular expression can also be written easier:

 public boolean checkDate(String dateToCheck) { return dateToCheck.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")); } 
+16
source

All Articles