检查特定模式

时间:2013-02-06 10:45:37

标签: java regex

我想检查字符串是否处于特定模式。

例如我想检查是否匹配模式的字符串:2012-02-20。

I.E:当x是数字时,xxxx-xx-xx。

有可能吗?有人说正则表达式。

5 个答案:

答案 0 :(得分:2)

使用此正则表达式\d{4}-\d{2}-\d{2}

用于检查用途:

yourString.matches(regexString);

答案 1 :(得分:2)

您可以使用SimpleDateFormat解析方法执行此操作:

final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

boolean matchesDateFormat(String date)
{
    try
    {
        format.parse(date);
        return true;
    }
    catch(ParseException e)
    {
        return false;
    }
}

当然,如果你以后继续解析日期,那么你可以跳过这个并尝试解析它。

答案 2 :(得分:2)

如果您想测试日期字符串是否为有效日期,请更好地使用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;
    }
}

答案 3 :(得分:1)

您可以检查字符串是否遵循4位数的确切格式,短划线-,2位数字,短划线-和2位数字@ burning_LEGION的正则表达式。但是,它不会检查String是否表示有效日期。您可以指定9999-99-99,它将通过验证。

使用SimpleDateFormat是检查String是否为有效日期的正确方法,它遵循给定的表示格式。除formatting a date之外,SimpleDateFormat也可用于从字符串中解析日期:parse(String)parse(String, ParsePosition)

默认情况下,SimpleDateFormat为 lenient ,这意味着它将允许2013-025-234等无意义的日期传递。使用setLenient(boolean lenient)false将解决此问题。

但是,另一个问题是它还会忽略有效日期之后的任何垃圾数据(例如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通过,我认为这是合理的宽大处理。如果您不想这样,可以在将String插入parse方法之前对正则表达式进行检查。

答案 4 :(得分:0)

您可以查看以下代码:

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