Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式模式在我从System.in获取字符串时匹配字符串,但在声明时不匹配_Java_Regex - Fatal编程技术网

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

Java正则表达式模式在我从System.in获取字符串时匹配字符串,但在声明时不匹配,java,regex,Java,Regex,我有一条手机短信,我想用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 InputStream

我有一条手机短信,我想用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,但第二个代码与日期不匹配。我错在哪里。

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

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

12/12/12
7/9/14

我怀疑第一个打印的是7/9/14,因为它只匹配7/9/1。此外,示例程序在我的计算机上运行良好。它们都适用于我。虽然可以改进regexp以匹配多个数字的日期。不相关,但是为什么需要引用/?i、 你不知道t@Mena我不经常使用正则表达式,所以我只是假设/是一个需要引用的特殊字符。谢谢你指出这一点。@qualebs不客气:谢谢你指出这一点,我正要测试像12/12/14这样的东西是否有效。我怎样才能得到两位数?这一带真绿
12/12/12
7/9/14