try
-アプローチは、これcatch
を行うための一般的に受け入れられている方法です。これは主に、有効な double が持つことができる形式が実際にはたくさんあるためです。
double a = 42.e10; // or 42.E10
double b = 42.f; // or 42.F
double c = 42.d; // or 42.D
double d = 010E010D;
double e = 0x1.fffffffffffffP+1023;
double f = 0x1.0p-1022;
これらはすべて有効な double であり、 を介して文字列から解析できますparseDouble()
。Double.parseDouble("NaN")
andDouble.parseDouble("Infinity")
も有効です (ただしNaN
、 andInfinity
はリテラルではありません)。言うまでもなくparseDouble()
、先頭または末尾の空白も扱います。だから私の答えは:しないでください!try
-catch
アプローチを使用します。有効な double 形式の一部 (またはすべて) に一致する正規表現を作成することはNumberFormatException
可能ですが、 .
完全な正規表現は、次のドキュメントで実際に説明されていますvalueOf()
。
無効な文字列でこのメソッドを呼び出してスローされることを避けるために、NumberFormatException
以下の正規表現を使用して入力文字列を選別できます。
final String Digits = "(\\p{Digit}+)";
final String HexDigits = "(\\p{XDigit}+)";
// an exponent is 'e' or 'E' followed by an optionally
// signed decimal integer.
final String Exp = "[eE][+-]?"+Digits;
final String fpRegex =
("[\\x00-\\x20]*"+ // Optional leading "whitespace"
"[+-]?(" + // Optional sign character
"NaN|" + // "NaN" string
"Infinity|" + // "Infinity" string
// A decimal floating-point string representing a finite positive
// number without a leading sign has at most five basic pieces:
// Digits . Digits ExponentPart FloatTypeSuffix
//
// Since this method allows integer-only strings as input
// in addition to strings of floating-point literals, the
// two sub-patterns below are simplifications of the grammar
// productions from section 3.10.2 of
// The Java™ Language Specification.
// Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
"((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
// . Digits ExponentPart_opt FloatTypeSuffix_opt
"(\\.("+Digits+")("+Exp+")?)|"+
// Hexadecimal strings
"((" +
// 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "(\\.)?)|" +
// 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
"(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
")[pP][+-]?" + Digits + "))" +
"[fFdD]?))" +
"[\\x00-\\x20]*");// Optional trailing "whitespace"
if (Pattern.matches(fpRegex, myString))
Double.valueOf(myString); // Will not throw NumberFormatException
else {
// Perform suitable alternative action
}
ご覧のとおり、やや厄介な正規表現です。