6

Can anybody tell me how I use a forward slash escape character in Java. I know backward slash is \ \ but I've 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!

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
pnefc
  • 105
  • 1
  • 2
  • 4

2 Answers2

19

You don't need to escape forward slashes either in Java as a language or in regular expressions.

Also note that blocks like this:

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

are more compactly and readably written as:

return condition;

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

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

Note that this isn't a terribly good way of testing for valid dates - it would probably be worth trying to parse it as a date as well or instead, ideally with an API which will allow you to do this without throwing an exception on failure.

Your regular expression can also be written more simply as:

public boolean checkDate(String dateToCheck) {
    return dateToCheck.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}"));
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you Jon, this answers my query. The reason I'm doing this in this way is because it's what the spec at University says. Left to my own devices, I would use the Java date object. – pnefc May 26 '11 at 07:19
  • You want to read this other question on verifying a date: http://stackoverflow.com/questions/226910/how-to-sanity-check-a-date-in-java – Basil Bourque Mar 11 '12 at 18:40
0

I wanted to write "n/a" and ended up with ""n\u002Fa""

P.Ellis
  • 55
  • 2
  • 10
  • This statement isn't very helpful. It doesn't answer the question at all and it appears to be asking a new one. – Garet Jax Feb 03 '22 at 13:32