java判断一个string能否转换为double_检查String中是否可以在Java中解析为Double的最快方法...

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

这是代码部分:

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:

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 the Java Language Specification,2nd

// edition,section 3.10.2.

// 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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值