Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Forward Slash Escape Character

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!

like image 407
pnefc Avatar asked May 24 '11 14:05

pnefc


People also ask

How do you escape a forward slash in Java?

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must be enclosed in quotation marks (""). These are the valid character literals.

How do you escape special characters in Java?

Strings - Special Characters The solution to avoid this problem, is to use the backslash escape character.

How do you escape a slash in a string?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.

What does a forward slash mean in Java?

In some programming languages, a forward slash is used to apply comment, or in the nonexecutable statement that means if you write anything between two sets of forward slashes, it will only not be read by computer machine because the comments in the programming languages do not consider as part of functional ...


1 Answers

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}"));
}
like image 52
Jon Skeet Avatar answered Oct 08 '22 08:10

Jon Skeet