Java - Forward Slash Escape Character

此生再无相见时 提交于 2019-12-01 17:41:16

问题


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!


回答1:


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}"));
}


来源:https://stackoverflow.com/questions/6111985/java-forward-slash-escape-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!