Java - 前向斜线逃脱字符 [英] Java - Forward Slash Escape Character
问题描述
有人可以告诉我如何在Java中使用正斜杠转义字符。我知道反斜杠是\ \,但我试过\ /和/ /没有运气!
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.
提前感谢!
推荐答案
您不需要使用Java作为语言或正则表达式转义前斜杠。
You don't need to escape forward slashes either in Java as a language or in regular expressions.
if (condition) {
return true;
} else {
return false;
}
更紧凑且可读性地写为:
are more compactly and readably written as:
return condition;
所以在你的case,我相信你的方法应该是:
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]"));
}
请注意,这不是测试有效日期的一种非常好的方法 - 它可能是值得尝试解析为作为一个日期,或者,或者,更理想的是一个API,这将允许你这样做而不抛出异常失败。
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}"));
}
这篇关于Java - 前向斜线逃脱字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!