Java Regex Time Validate parseTime(String value)

Here you can find the source of parseTime(String value)

Description

Parse value of TM property.

License

Open Source License

Return

The (pre-byoyomi-)time in milliseconds or -1, if the format was not recognized

Declaration

public static long parseTime(String value) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /** Parse value of TM property.
    According to FF4, TM needs to be a real value, but older SGF versions
    allow a string with unspecified content. We try to parse a few known
    formats.//from w  w w . j a  va  2 s  .c om
    @return The (pre-byoyomi-)time in milliseconds or -1, if the
    format was not recognized */
    public static long parseTime(String value) {
        value = value.trim();
        try {
            return (long) (Double.parseDouble(value) * 1000);
        } catch (NumberFormatException e1) {
        }
        try {
            Pattern pattern;
            Matcher matcher;

            // Pattern as written by CGoban 1.9.12
            pattern = Pattern.compile("(\\d{1,2}):(\\d{2})");
            matcher = pattern.matcher(value);
            if (matcher.matches()) {
                assert matcher.groupCount() == 2;
                return (Integer.parseInt(matcher.group(1)) * 60000L + Integer.parseInt(matcher.group(2)) * 1000L);
            }

            pattern = Pattern.compile("(\\d+):(\\d{2}):(\\d{2})");
            matcher = pattern.matcher(value);
            if (matcher.matches()) {
                assert matcher.groupCount() == 3;
                return (Integer.parseInt(matcher.group(1)) * 3600000L + Integer.parseInt(matcher.group(2)) * 60000L
                        + Integer.parseInt(matcher.group(3)) * 1000L);
            }

            pattern = Pattern.compile("(\\d+)\\s*(?:h|hr|hrs|hours|hours)(?:\\s+each)?+");
            matcher = pattern.matcher(value);
            if (matcher.matches()) {
                assert matcher.groupCount() == 1;
                return Integer.parseInt(matcher.group(1)) * 3600000L;
            }

            pattern = Pattern.compile("(\\d+)\\s*(?:m|min)");
            matcher = pattern.matcher(value);
            if (matcher.matches()) {
                assert matcher.groupCount() == 1;
                return Integer.parseInt(matcher.group(1)) * 60000L;
            }
        } catch (NumberFormatException e2) {
            assert false; // patterns should match only valid integers
        }
        return -1;
    }
}

Related

  1. parseTime(String s)
  2. parseTime(String str)
  3. parseTime(String t)
  4. parseTimeDifference(String input)
  5. parseTimeOffset(String s)
  6. parseTimePeriod(String period)
  7. parseTimePeriod(String s)