Java regular expression (edit date)
package com.mmm.http;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.mmm.model.AppField;
public class EditDate {
public static String editDate(String date, int type) {
String msg = null;
String patrn = pattern(type);
Pattern pat = Pattern.compile(patrn);
Matcher matcher = pat.matcher(date);
if (!matcher.find()) {
msg = "Invalid date format.";
}
return msg;
}
public static String pattern(int type) {
String p = "";
switch (type) {
case AppField.DATE_ISO:
//must be nnnn-nn-nn
p = "\\d{4}-\\d{2}-\\d{2}"; // ISO
break;
case AppField.DATE_USA:
p = "\\d{2}/\\d{2}/\\d{4}";
break;
case AppField.DATE_EUR:
p = "\\d{4}.\\d{2}.\\d{2}";
break;
default:
p = "\\d{4}-\\d{2}-\\d{2}"; // ISO
break;
}
p = "^" + p + "$"; //important!
return p;
}
public static void main(String[] args) {
System.out.println("msg=" + editDate("2000-10-10", 24));
System.out.println("msg=" + editDate("22/12/1999", 25));
System.out.println("msg=" + editDate("11/11/99", 20));
}
}
Some Predefined Character Classes:
. Any character (may or may not match line terminators)
\d A digit: [0-9]
\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
0 Comments:
Post a Comment
<< Home