Class Parsers

java.lang.Object
com.google.common.labs.parse.Parsers

public final class Parsers extends Object
Some common composite parsers in addition to the core parsers provided by Parser.
Since:
10.8
  • Field Details

    • UNSIGNED_DECIMAL

      public static final Parser<String> UNSIGNED_DECIMAL
      Parses unsigned decimal point numbers, e.g., 1.23, 0.0, 15, 0.

      To support signs, you can compose it like:

      
       Parser<Double> signedDecimal = sequence(
           one('-').thenReturn(-1).orElse(1), UNSIGNED_DECIMAL.map(Double::parseDouble),
           (sign, num) -> sign * num);
       
    • DURATION

      public static final Parser<Duration> DURATION
      Parses duration in the shorthand format of 1.5h, 30d, 10m30s etc.

      Matches one or more unit specs consisting of a positive decimal number followed by a unit suffix. For example:

      • "30s" -> 30 seconds
      • "2h30m" -> 2 hours and 30 minutes
      • "1w2d" -> 9 days (1 week + 2 days)
      • "1.5h" -> 1 hour and 30 minutes

      Supported units:

      • w (weeks) - treated as exactly 7 days
      • d (days) - treated as exactly 24 hours
      • h (hours)
      • m (minutes)
      • s (seconds)
      • ms (milliseconds)
      • us (microseconds)
      • ns (nanoseconds)

      Note:

      • The duration components must be specified in strictly descending order of unit size (e.g., "1d2h" is allowed, but "2h1d" or "1d1d" are not).
      • Only the last component can contain a decimal point (e.g., "1.5h" or "1h2.5m" are allowed, but "1.5h2m" is not).
      • Negative values (e.g., "-2s") are not supported.
    • BMP_CODE_UNIT

      public static final Parser<Integer> BMP_CODE_UNIT
      Parses a 4-digit hex BMP code unit. The following example parses a surrogate pair of two UTF-16 code units and will return the emoji 😀:
      
       BMP_CODE_UNIT
           .map(Character::toString)
           .zeroOrMore(Collectors.joining())
           .parse("D83DDE00");
       

      Note that starting from v9.6, it's recommended to use Joiner ( Joiner.on(delimiter)) in place of JDK Collectors.joining(delimiter) because Joiner optimizes for single-string input, which is a common case in the context of parsing.

      You can also compose it with Parser.quotedByWithEscapes():

      
       Parser.quotedByWithEscapes('"', '"', Parser.string("u").then(BMP_CODE_UNIT).map(Character::toString));