這很奇怪,因爲它是非常簡單的dd/mm
格式的正則表達式。結果應該是:"Group 1: 14; Group 2: 12"
,但它是"Group 1: 14; Group 2: 1"
。正則表達式的日期省略了一個月份的字符
第二組只捕獲第一個字符,但省略第二個字符(示例中的'2')。
String sDay = "(?:0?[1-9]|[12][0-9]|3[01])";
String sMonth = "(?:0?[1-9]|1[0-2])";
String sDot = "[\\.]";
String sSlash = "[/]";
String sMinus = "[\\-]";
String sSeparators = (sDot + "|" + sSlash + "|" + sMinus);
Pattern reDayMonth =
Pattern.compile("(" + sDay + ")" + "(?:" + sSeparators + ")" + "(" + sMonth+ ")");
String s = "14/12";
Matcher reMatcher = reDayMonth.matcher(s);
boolean found = reMatcher.find();
System.out.println("Group 1: " + reMatcher.group(1) + "; Group 2: " + reMatcher.group(2));
我不明白爲什麼。你可以幫我嗎?
當多個替代方案可以匹配時,首先放置最長的替代方案。 – ridgerunner