Discuss / Java / 正则分组匹配 练习

正则分组匹配 练习

Topic source

保持热爱

#1 Created at ... [Delete] [Delete and Lock User]
public static void main(String[] args) {
    System.out.println(Arrays.toString(parseTime("21:05:19")));
}

public static int[] parseTime(String s) {
    Pattern pattern = Pattern.compile("([0-24]{2}):([0-59]{2}):([0-59]{2})");
    Matcher matcher = pattern.matcher(s);
    int[] times = new int[3];
    if (matcher.matches()) {
        times[0] = Integer.valueOf(matcher.group(1));
        times[1] = Integer.valueOf(matcher.group(2));
        times[2] = Integer.valueOf(matcher.group(3));
    } else {
        throw new IllegalArgumentException();
    }
    return times;
}

  • 1

Reply