当我从System.in获取字符串但未声明时,Java正则表达式模式匹配字符串

时间:2014-09-18 11:11:31

标签: java regex

我手机中有以下短信,我想使用正则表达式提取发送日期。

public static void main(String[] args){

    // this is the regex I input in the console [0-9]\Q/\E[0-9]\Q/\E[0-9] to match any date 
    //in the form dd/mm/yy

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter your regex: ");
    Pattern pattern = Pattern.compile(reader.readLine());
    System.out.println("Enter string to match: ");

    // the string I read from the console is in the form 
    // P67XDF9K7 confirmed you have received Ksh4,033.00 from 254723981091 on 7/9/14 at 6:45PM your new M-PESA balance is Ksh9,5033 M-PESA PIN YAKO SIRI YAKO

    String message = reader.readLine();
    Matcher matcher = pattern.matcher(message);
    System.out.println(matcher.find() ? matcher.group() : "no match found");
}

当我在这个程序中尝试相同时,我收到一个错误,字符串没有垫

public static void main(String[] args){

    String regex = "[0-9]\\Q/\\E[0-9]\\Q/\\E[0-9]";
    Pattern pattern = Pattern.compile(regex);
    String message = "P67XDF9K7 confirmed you have received Ksh4,033.00 from 254723981091 on 7/9/14 at 6:45PM your new M-PESA balance is Ksh9,5033 M-PESA PIN YAKO SIRI YAKO";
    Matcher matcher = pattern.matcher(message);
    System.out.println(matcher.find() ? matcher.group() : "no match found");
}

如果我没有错误输入代码,第一个代码会正确匹配日期并打印出7/9/14但第二个代码与日期不匹配。我哪里错了。

1 个答案:

答案 0 :(得分:0)

您需要在正则表达式中指定最后必须有两位数字。

[0-9]{1,2}\\Q/\\E[0-9]{1,2}\\Q/\\E[0-9]{2}

DEMO

String s = "P67XDF9K7 12/12/12 confirmed you have  received Ksh4,033.00 from 254723981091 on 7/9/14 at 6:45PM your new M-PE";
Pattern p = Pattern.compile("[0-9]{1,2}\\Q/\\E[0-9]{1,2}\\Q/\\E[0-9]{2}");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.println(m.group(0));
}

输出:

12/12/12
7/9/14