我想检查一个字符串是否处于某种模式。
例如我想检查一个字符串是否匹配模式:2012-02-20。
IE: xxxx-xx-xx 当 x 是一个数字。
是否可以?有人说正则表达式。
使用这个正则表达式\d{4}-\d{2}-\d{2}
检查用途:
yourString.matches(regexString);
您可以使用SimpleDateFormat解析方法来做到这一点:
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
boolean matchesDateFormat(String date)
{
try
{
format.parse(date);
return true;
}
catch(ParseException e)
{
return false;
}
}
当然,如果您稍后继续解析日期,那么您可以跳过这个并尝试解析它。
如果要测试日期字符串是否为有效日期,最好使用SimpleDateFormat
检查。不要使用正则表达式进行验证,月份是 13 怎么样?日期是 50?闰年?
一些例子:
public boolean isValidDate(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
}
您可以使用@burning_LEGION 的正则表达式检查字符串是否遵循 4 位数字、一个破折号-
、2 个数字、一个破折号和 2 个数字的确切格式。-
但是,它不检查字符串是否代表有效日期。您可以指定9999-99-99
,它将通过验证。
使用SimpleDateFormat是检查字符串是否为有效日期并且它遵循给定的表示格式的正确方法。SimpleDateFormat,除了格式化一个日期,也可以用来从字符串解析日期:parse(String)
,parse(String, ParsePosition)
。
默认情况下, SimpleDateFormat 是lenient,这意味着它将允许无意义的日期,例如2013-025-234
通过。使用setLenient(boolean lenient)
tofalse
将解决这个问题。
然而,另一个问题是它也会忽略任何在有效日期之后的垃圾数据(例如2012-03-23garbage#$%$#%
)。设置 lenient 并不能解决这个问题。我们需要用parse(String, ParsePosition)
方法检查最后一个位置。
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
// Make the parsing strict - otherwise, it is worse than regex solution
dateFormatter.setLenient(false);
Date date = null;
ParsePosition pos = new ParsePosition(0);
date = dateFormatter.parse(inputString, pos);
if (date != null && pos.getIndex() == inputString.length()) {
// These 3 points are ensured:
// - The string only contains the date.
// - The date follows the format strictly.
// - And the date is a valid one.
} else {
// Valid date but string contains other garbage
// Or the string has invalid date or garbage
}
SimpleDateFormat
将允许2013-1-5
通过,我认为这是一个合理的宽大处理。如果您不希望这样做,您可以在将字符串插入parse
方法之前对正则表达式进行检查。
您可以检查以下代码:
public void test() {
String REG_EXP = "(\\d{4}-[0,1]?\\d{1}-[0,1,2,3]?\\d{1})"; //yyyy-mm-dd formate this can not check boundary condition something like this... 1981-02-30
String REG_EXP1 = "(\\d{4}-\\d{2}-\\d{2})"; // if u just want xxxx-xx-xx where x is number
String input = "date1 1981-09-06 wrong date 9999-22-22 date2 1981-9-09 date3 1981-11-1 date4";
Pattern pattern = Pattern.compile(REG_EXP);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}