检查String中是否可以在Java中解析为Double的最快方法

前端之家收集整理的这篇文章主要介绍了检查String中是否可以在Java中解析为Double的最快方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道有一百万种方式做到这一点,但最快的是什么?这应该包括科学记数法.

注意:我没有兴趣将值转换为Double,我只想知道是否可能.即private boolean isDouble(String value).

解决方法

您可以使用Double类使用的相同正则表达式来检查它.这里有很好的记录:

http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#valueOf%28java.lang.String%29

这是代码部分:

To avoid calling this method on an invalid string and having a NumberFormatException be thrown,the regular expression below can be used to screen the input string:

  1. final String Digits = "(\\p{Digit}+)";
  2. final String HexDigits = "(\\p{XDigit}+)";
  3.  
  4. // an exponent is 'e' or 'E' followed by an optionally
  5. // signed decimal integer.
  6. final String Exp = "[eE][+-]?"+Digits;
  7. final String fpRegex =
  8. ("[\\x00-\\x20]*"+ // Optional leading "whitespace"
  9. "[+-]?(" + // Optional sign character
  10. "NaN|" + // "NaN" string
  11. "Infinity|" + // "Infinity" string
  12.  
  13. // A decimal floating-point string representing a finite positive
  14. // number without a leading sign has at most five basic pieces:
  15. // Digits . Digits ExponentPart FloatTypeSuffix
  16. //
  17. // Since this method allows integer-only strings as input
  18. // in addition to strings of floating-point literals,the
  19. // two sub-patterns below are simplifications of the grammar
  20. // productions from the Java Language Specification,2nd
  21. // edition,section 3.10.2.
  22.  
  23. // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt
  24. "((("+Digits+"(\\.)?("+Digits+"?)("+Exp+")?)|"+
  25.  
  26. // . Digits ExponentPart_opt FloatTypeSuffix_opt
  27. "(\\.("+Digits+")("+Exp+")?)|"+
  28.  
  29. // Hexadecimal strings
  30. "((" +
  31. // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt
  32. "(0[xX]" + HexDigits + "(\\.)?)|" +
  33.  
  34. // 0[xX] HexDigits_opt . HexDigits BinaryExponent FloatTypeSuffix_opt
  35. "(0[xX]" + HexDigits + "?(\\.)" + HexDigits + ")" +
  36.  
  37. ")[pP][+-]?" + Digits + "))" +
  38. "[fFdD]?))" +
  39. "[\\x00-\\x20]*");// Optional trailing "whitespace"
  40.  
  41. if (Pattern.matches(fpRegex,myString))
  42. Double.valueOf(myString); // Will not throw NumberFormatException
  43. else {
  44. // Perform suitable alternative action
  45. }

猜你在找的Java相关文章