Java - Forward Slash Escape Character

后端 未结 1 849
走了就别回头了
走了就别回头了 2021-01-18 07:37

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:-

相关标签:
1条回答
  • 2021-01-18 08:13

    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}"));
    }
    
    0 讨论(0)
提交回复
热议问题