001
002 /*
003 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004 *
005 * $Id: DoubleFormat.java 117 2011-08-28 16:29:12Z archie.cobbs $
006 */
007
008 package org.dellroad.stuff.string;
009
010 import java.util.regex.Pattern;
011
012 /**
013 * Java double string format regular expression. Adapted from the {@link Double#valueOf(String)} Javadoc.
014 */
015 public final class DoubleFormat {
016
017 /**
018 * Regular expression which matches strings which are valid as input to {@link Double#valueOf(String)}.
019 */
020 public static final Pattern PATTERN;
021
022 private static final String DIGITS = "(\\p{Digit}+)";
023
024 private static final String HEX_DIGITS = "(\\p{XDigit}+)";
025
026 // an exponent is 'e' or 'E' followed by an optionally
027 // signed decimal integer.
028 private static final String EXPONENT = "[eE][+-]?" + DIGITS;
029
030 private static final String REGEX =
031 "[+-]?(" // Optional sign character
032 + "NaN|" // "NaN" string
033 + "Infinity|" // "Infinity" string
034
035 // A decimal floating-point string representing a finite positive
036 // number without a leading sign has at most five basic pieces:
037 // Digits . Digits ExponentPart FloatTypeSuffix
038 //
039 // Since this method allows integer-only strings as input
040 // in addition to strings of floating-point literals, the
041 // two sub-patterns below are simplifications of the grammar
042 // productions from the Java Language Specification, 2nd
043 // edition, section 3.10.2.
044
045 // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
046 + "(((" + DIGITS + "(\\.)?(" + DIGITS + "?)(" + EXPONENT + ")?)|"
047
048 // . Digits ExponentPart_opt FloatTypeSuffix_opt
049 + "(\\.(" + DIGITS + ")(" + EXPONENT + ")?)|"
050
051 // Hexadecimal strings
052 + "(("
053 // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
054 + "(0[xX]" + HEX_DIGITS + "(\\.)?)|"
055
056 // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
057 + "(0[xX]" + HEX_DIGITS + "?(\\.)" + HEX_DIGITS + ")"
058 + ")[pP][+-]?" + DIGITS + "))" + "[fFdD]?))";
059
060 static {
061 PATTERN = Pattern.compile(REGEX);
062 }
063
064 private DoubleFormat() {
065 }
066 }
067