[英]Pattern Matches for Date Format: dd.MM.yyyy, MM.yyyy and yyyy
I need to check a date for a given string. 我需要检查给定字符串的日期。 The string that I get isn't regular and I don't want to use Dateformat
or something like this. 我得到的字符串不是常规的,并且我不想使用Dateformat
或类似的东西。 I'm trying to avoid getting multiple exceptions. 我试图避免出现多个异常。 I need a regex for dd.MM.yyyy
and MM.yyyy
and yyyy
. 我需要一个用于dd.MM.yyyy
和MM.yyyy
和yyyy
的正则表达式。 At first I had 起初我有
\\d+\\.?\\d+\\.?\\d+
but this isn't working. 但这不起作用。
If you really want to use a regex , here is a basic working example: 如果您真的想使用regex ,那么这是一个基本的工作示例:
String regex = "([0-9]{2}\\.){0,2}([0-9]{4})";
assert "03.2017".matches(regex);
assert "31.03.2017".matches(regex);
assert "2017".matches(regex);
assert !"23-2017".matches(regex);
Note that: 注意:
0013
) or incorrect days/months (day 45 or month 15) 它不会检测到错误的年份(例如0013
)或错误的天/月(第45天或第15个月) To really check for dates, I suggest you use libraries especially made for this, like DateFormat
, JodaTime
or apache's DateUtils
. 要真正检查日期,建议您使用专门为此设计的库,例如DateFormat
, JodaTime
或apache的DateUtils
。
Using DateTimeFormatter : 使用DateTimeFormatter :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[[dd.]MM.]yyyy");
// correct dates
assert formatter.parse("31.12.2017") != null;
assert formatter.parse("12.2017") != null;
assert formatter.parse("2017") != null;
// wrong date
assert formatter.parse("31.2017") == null;
Using DateUtils ( maven link ): 使用DateUtils ( maven链接 ):
String[] acceptedFormats = {"dd.MM.yyyy", "dd.MM.yyyy", "dd/MM/yyyy"};
// correct dates
assert DateUtils.parseDate("07.12.2017", acceptedFormats) != null;
assert DateUtils.parseDate("07.2017", acceptedFormats) != null;
assert DateUtils.parseDate("2017", acceptedFormats) != null;
assert DateUtils.parseDate("2017", acceptedFormats) != null;
// wrong dates
assert DateUtils.parseDate("123.2012", acceptedFormats) == null;
assert DateUtils.parseDate("01.13.2012", acceptedFormats) == null;
Could you try the below 你可以尝试以下
String regex = "([0-9]{2})-([0-9]{2})-([0-9]{4})";
which will match the date dd-mm-yyyy 它将与日期dd-mm-yyyy匹配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.