如何检查String中的String是否为数字

Cra*_*gus 838 java string numeric

在解析之前,如何检查字符串是否为数字?

Cra*_*gTP 875

这通常使用简单的用户定义函数(即Roll-your-own"isNumeric"函数)完成.

就像是:

public static boolean isNumeric(String str) { 
  try {  
    Double.parseDouble(str);  
    return true;
  } catch(NumberFormatException e){  
    return false;  
  }  
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你正在调用这个函数很多,并且你期望许多检查由于不是一个数字而失败,那么这个机制的性能将不会很好,因为你依赖于每次失败抛出的异常,这是一个相当昂贵的操作.

另一种方法可能是使用正则表达式来检查作为数字的有效性:

public static boolean isNumeric(String str) {
  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
}
Run Code Online (Sandbox Code Playgroud)

但是,请注意上面的RegEx机制,因为如果您使用的是非阿拉伯数字(即0到9之间的数字),它将会失败.这是因为RegEx的"\ d"部分只匹配[0-9],并且实际上并不具有国际数字意义.(感谢OregonGhost指出这一点!)

或者甚至另一种选择是使用Java的内置java.text.NumberFormat对象来查看解析字符串后解析器位置是否在字符串的末尾.如果是,我们可以假设整个字符串是数字:

public static boolean isNumeric(String str) {
  NumberFormat formatter = NumberFormat.getInstance();
  ParsePosition pos = new ParsePosition(0);
  formatter.parse(str, pos);
  return str.length() == pos.getIndex();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,正则表达式中的`.`将匹配任何字符,而不仅仅是小数分隔符. (11认同)
  • +1用于实现try/catch的费用.从长远来看,这实际上是一种可怕的重复使用方法,但实际上我们在Java中坚持使用它. (9认同)
  • Java Regex中的\ d只匹配拉丁数字吗?如果它像.NET正则表达式,你将遇到其他(例如阿拉伯语)数字的问题,如下所述:http://blogs.msdn.com/oldnewthing/archive/2004/03/09/86555.aspx (7认同)
  • 注意,没有诸如"拉丁数字"之类的东西,数字0-9实际上是阿拉伯数字.人们可能熟悉罗马数字,这些数字被拉丁语的人使用,形式为I,II,III,IV,V,VI等.https://en.wikipedia.org/wiki/Arabic_numerals; https://en.wikipedia.org/wiki/Roman_numerals (4认同)
  • numberFormatter解决方案可能只比捕获NumberFormatException更好.我怀疑最好的方法是使用正则表达式. (3认同)
  • 在最后一个命题(NumberFormat)中,您在parse方法中缺少空检查.否则isNumeric("")将返回true,因为位置索引将保持不变! (3认同)
  • 处理指数 (**+1.3E10**): `return str.matches("\\d") && str.matches("^[+-]?\\d*\\.?\\d*( [eE]\\d)?\\d*$");` (2认同)
  • 另外,不要忘记`.006`和`0.`-这些也是有效的. (2认同)
  • 如果可扩展地使用,两种解决方案都是不好的 抛出异常是昂贵的,并且创建正则表达式也是昂贵的.必须创建一次正则表达式并重复使用. (2认同)

pal*_*int 662

使用Apache Commons Lang 3.5及以上版本:NumberUtils.isCreatableStringUtils.isNumeric.

使用Apache Commons Lang 3.4及以下版本:NumberUtils.isNumberStringUtils.isNumeric.

您还可以使用StringUtils.isNumericSpace哪个返回true空字符串并忽略字符串中的内部空格.另一种方法是使用StringUtils.isParsable它基本上检查数字是否可以根据Java进行解析.(链接的javadoc包含每种方法的详细示例.)

  • `StringUtils.isNumeric()`可能不合适,因为它只检查字符串是否是数字序列.对于大多数的整数都可以,但对于带小数的数字,组分隔符等则不是这样. (57认同)
  • 重新发明轮子,因为你不包括整个库,因为你需要在一个地方使用3行功能. (40认同)
  • 是否真的值得为此功能添加**整个**库?显然,如果它与其他很好用的东西一起使用,但考虑到人们已经在一行代码中解决了这个问题,这可能有点过头了. (10认同)
  • 不适用于否定.所有数字中有一半是负数,所以...... (7认同)
  • @PaulDraper:你是对的,`StringUtils`不支持前导符号,但你应该检查`NumberUtils.isCreatable`,它正确支持否定. (4认同)
  • @JUG:thx为抬头.奇怪的是,文档链接说相反,也许是因为更新的版本(注意答案是在评论发布后几天编辑的) (2认同)
  • @JUG:搜索到它,这就是我的想法,一些以前的版本,即.[Commons Lang版本2.4 stringutils.isNumeric()的行为与你说的一样(对于空字符串返回true)](http://commons.apache.org/proper/commons-lang/javadocs/api-2.4/org/apache/commons /lang/StringUtils.html#isNumeric(java.lang.String)) (2认同)
  • NumberUtils.isParsable(String str)方法可用于检查给定的字符串是否为数字,这适用于所有情况。 (2认同)

Ahm*_*ejo 146

如果你在Android上,那么你应该使用:

android.text.TextUtils.isDigitsOnly(CharSequence str)
Run Code Online (Sandbox Code Playgroud)

文档可以在这里找到

保持简单.大多数人都可以"重新编程"(同样的事情).

  • 注意:这会导致NPE为空输入.此外,不适用于负数或小数. (8认同)
  • 这不适用于123.456;( (7认同)
  • @ kape123 :)确定"123.456"不包含数字. (4认同)
  • 我喜欢!!我认为这绝对是数字。不适用于`.`,`-` (2认同)

Ibr*_*ief 121

正如@CraigTP在其出色的答案中所提到的,我在使用Exceptions测试字符串是否为数字时也有类似的性能问题.所以我最终分裂字符串并使用java.lang.Character.isDigit().

public static boolean isNumeric(String str)
{
    for (char c : str.toCharArray())
    {
        if (!Character.isDigit(c)) return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

根据Javadoc,Character.isDigit(char)将正确识别非拉丁数字.在性能方面,我认为简单的N次比较,其中N是字符串中的字符数,与进行正则表达式匹配相比,计算效率更高.

更新:正如Jean-FrançoisCorbett在评论中所指出的,上面的代码只会验证正整数,它涵盖了我的大多数用例.下面是更新的代码,它根据系统中使用的默认语言环境正确验证十进制数,并假设小数分隔符仅在字符串中出现一次.

public static boolean isStringNumeric( String str )
{
    DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
    char localeMinusSign = currentLocaleSymbols.getMinusSign();

    if ( !Character.isDigit( str.charAt( 0 ) ) && str.charAt( 0 ) != localeMinusSign ) return false;

    boolean isDecimalSeparatorFound = false;
    char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();

    for ( char c : str.substring( 1 ).toCharArray() )
    {
        if ( !Character.isDigit( c ) )
        {
            if ( c == localeDecimalSeparator && !isDecimalSeparatorFound )
            {
                isDecimalSeparatorFound = true;
                continue;
            }
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 小数分隔符是否也会导致失败? (4认同)
  • 调用toCharArray()将在String对象中创建数组的副本,因为String是不可变的。直接在String对象上使用`charAt(int index)`方法可能更快。 (3认同)
  • -ve标志会失败吗? (2认同)
  • 传递长度为0的字符串时将生成`StringIndexOutOfBoundsException`。可以通过`if(str.length()== 0)返回false;来修复。 (2认同)

Max*_*ysh 106

Java 8 lambda表达式.

String someString = "123123";
boolean isNumeric = someString.chars().allMatch( Character::isDigit );
Run Code Online (Sandbox Code Playgroud)

  • 它会为"-1"产生什么? (14认同)
  • 这个答案简洁,简单,易读.你几乎可以像英语一样阅读它 - "chars all match digits".它不需要第三方库.它在非例外情​​况下不使用例外.这应该成为公认的答案. (8认同)
  • 您也可以使用方法引用:someString.chars().allMatch(Character :: isDigit) (4认同)
  • 很好,但它仍然重新发明轮子几乎所有"解决方案"在这里.此外,'null'失败(几乎所有其他人都失败). (3认同)
  • 没有正确的答案。数字字符串可以包含非数字字符(例如“。”或“-”),并且仍然是完美的数字。例如0.5,-1和1,000都将因此答案而失败,但是它们是完美的数值。 (2认同)

quu*_*x00 43

谷歌的番石榴库提供了一个很好的辅助方法来做到这一点:Ints.tryParse.您可以使用它,Integer.parseIntnull如果字符串不解析为有效整数,则返回而不是抛出异常.请注意,它返回Integer,而不是int,因此您必须将其转换/ autobox返回int.

例:

String s1 = "22";
String s2 = "22.2";
Integer oInt1 = Ints.tryParse(s1);
Integer oInt2 = Ints.tryParse(s2);

int i1 = -1;
if (oInt1 != null) {
    i1 = oInt1.intValue();
}
int i2 = -1;
if (oInt2 != null) {
    i2 = oInt2.intValue();
}

System.out.println(i1);  // prints 22
System.out.println(i2);  // prints -1
Run Code Online (Sandbox Code Playgroud)

然而,截至目前的发布 - 番石榴r11 - 它仍然标记为@Beta.

我没有对它进行基准测试.查看源代码,从很多健全性检查中得到了一些开销,但最终他们使用的Character.digit(string.charAt(idx)),与上面@Ibrahim的答案相似,但略有不同.在实现中没有异常处理开销.


Goo*_*oot 28

不要使用例外来验证您的值. 使用Util libs代替apache NumberUtils:

NumberUtils.isNumber(myStringValue);
Run Code Online (Sandbox Code Playgroud)

编辑:

请注意,如果您的字符串以0开头,则NumberUtils会将您的值解释为十六进制.

NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false
Run Code Online (Sandbox Code Playgroud)

  • 三年前接受的答案已经涵盖了`Number.isNumber()`. (7认同)
  • @Goot - 接受答案的历史记录表明`Number.isNumber()`出现在答案的第一个版本中,日期为12月24日17:01. (2认同)

Wat*_*ter 22

为什么每个人都在推动异常/正则表达式解决方案?

虽然我可以理解大多数人都习惯使用try/catch,但如果你想经常这样做......那可能会非常费力.

我在这里做的是采用正则表达式,parseNumber()方法和数组搜索方法来查看哪个是最有效的.这一次,我只看了整数.

public static boolean isNumericRegex(String str) {
    if (str == null)
        return false;
    return str.matches("-?\\d+");
}

public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    char[] data = str.toCharArray();
    if (data.length <= 0)
        return false;
    int index = 0;
    if (data[0] == '-' && data.length > 1)
        index = 1;
    for (; index < data.length; index++) {
        if (data[index] < '0' || data[index] > '9') // Character.isDigit() can go here too.
            return false;
    }
    return true;
}

public static boolean isNumericException(String str) {
    if (str == null)
        return false;
    try {  
        /* int i = */ Integer.parseInt(str);
    } catch (NumberFormatException nfe) {  
        return false;  
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我获得的速度结果如下:

Done with: for (int i = 0; i < 10000000; i++)...

With only valid numbers ("59815833" and "-59815833"):
    Array numeric took 395.808192 ms [39.5808192 ns each]
    Regex took 2609.262595 ms [260.9262595 ns each]
    Exception numeric took 428.050207 ms [42.8050207 ns each]
    // Negative sign
    Array numeric took 355.788273 ms [35.5788273 ns each]
    Regex took 2746.278466 ms [274.6278466 ns each]
    Exception numeric took 518.989902 ms [51.8989902 ns each]
    // Single value ("1")
    Array numeric took 317.861267 ms [31.7861267 ns each]
    Regex took 2505.313201 ms [250.5313201 ns each]
    Exception numeric took 239.956955 ms [23.9956955 ns each]
    // With Character.isDigit()
    Array numeric took 400.734616 ms [40.0734616 ns each]
    Regex took 2663.052417 ms [266.3052417 ns each]
    Exception numeric took 401.235906 ms [40.1235906 ns each]

With invalid characters ("5981a5833" and "a"):
    Array numeric took 343.205793 ms [34.3205793 ns each]
    Regex took 2608.739933 ms [260.8739933 ns each]
    Exception numeric took 7317.201775 ms [731.7201775 ns each]
    // With a single character ("a")
    Array numeric took 291.695519 ms [29.1695519 ns each]
    Regex took 2287.25378 ms [228.725378 ns each]
    Exception numeric took 7095.969481 ms [709.5969481 ns each]

With null:
    Array numeric took 214.663834 ms [21.4663834 ns each]
    Regex took 201.395992 ms [20.1395992 ns each]
    Exception numeric took 233.049327 ms [23.3049327 ns each]
    Exception numeric took 6603.669427 ms [660.3669427 ns each] if there is no if/null check
Run Code Online (Sandbox Code Playgroud)

免责声明:我并未声称这些方法是100%优化的,它们仅用于演示数据

当且仅当数字是4个字符或更少时,例外,并且每个字符串总是一个数字......在这种情况下,为什么甚至要检查?

简而言之,如果你经常使用try/catch遇到无效数字会非常痛苦,这是有道理的.我一直遵循的一条重要规则是永远不要将try/catch用于程序流程.这是一个例子.

有趣的是,简单的如果char <0 || > 9非常易于编写,易于记忆(并且应该以多种语言工作)并且几乎赢得了所有测试场景.

唯一的缺点是我猜测Integer.parseInt()可能会处理非ASCII数字,而数组搜索方法却没有.


对于那些想知道为什么我说很容易记住字符数组的人,如果你知道没有负面的迹象,你可以很容易地得到一些浓缩的东西:

public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    for (char c : str.toCharArray())
        if (c < '0' || c > '9')
            return false;
    return true;
Run Code Online (Sandbox Code Playgroud)

最后作为最后一点,我对所接受的例子中的分配运营商感到好奇,所有的选票都是.添加分配

double d = Double.parseDouble(...)
Run Code Online (Sandbox Code Playgroud)

因为你甚至没有使用这个值,所以它不仅没用,而且浪费了处理时间并将运行时间增加了几纳秒(这导致测试增加了100-200毫秒).我不明白为什么有人会这样做,因为它实际上是减少性能的额外工作.

您认为这将被优化出来......虽然我可能应该检查字节码并查看编译器正在做什么.这并没有解释为什么它总是显得更长,但如果它以某种方式被优化了...因此我想知道发生了什么.作为注释:更长一点,我的意思是运行测试10000000次迭代,并且多次运行该程序(10x +)总是显示它更慢.

编辑:更新了Character.isDigit()的测试

  • 这不是每次编译一个新的正则表达式吗?这看起来效率不高. (4认同)

use*_*985 18

public static boolean isNumeric(String str)
{
    return str.matches("-?\\d+(.\\d+)?");
}
Run Code Online (Sandbox Code Playgroud)

CraigTP的正则表达式(如上所示)会产生一些误报.例如,"23y4"将被计为数字,因为'.' 匹配任何不是小数点的字符.

它还会拒绝带有前导'+'的任何数字

避免这两个小问题的替代方案是

public static boolean isNumeric(String str)
{
    return str.matches("[+-]?\\d*(\\.\\d+)?");
}
Run Code Online (Sandbox Code Playgroud)


Art*_*ger 12

你可以使用NumberFormat#parse:

try
{
     NumberFormat.getInstance().parse(value);
}
catch(ParseException e)
{
    // Not a number.
}
Run Code Online (Sandbox Code Playgroud)

  • 如果可扩展地使用,则成本很高 (5认同)

Ket*_*eke 12

我们可以尝试用("")替换给定字符串中的所有数字,即空格,如果之后字符串的长度为零,那么我们可以说给定的字符串只包含数字.[如果你觉得这个答案有帮助那么请考虑投票吧]示例:

boolean isNumber(String str){
        if(str.length() == 0)
            return false; //To check if string is empty

        if(str.charAt(0) == '-')
            str = str.replaceFirst("-","");// for handling -ve numbers

        System.out.println(str);

        str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points

        if(str.length() == 0)
            return false; // to check if it is empty string after removing -ve sign and decimal point
        System.out.println(str);

        return str.replaceAll("[0-9]","").length() == 0;
    }
Run Code Online (Sandbox Code Playgroud)


Eri*_*Guo 11

如果您使用java开发Android应用程序,则可以使用TextUtils.isDigitsOnly函数.


小智 8

这是我对这个问题的回答.

捕获所有方便的方法,您可以使用任何类型的解析器来解析任何String : isParsable(Object parser, String str). 解析器可以是a Classobject.这也将允许您使用您编写的自定义解析器,并且应该适用于任何场景,例如:

isParsable(Integer.class, "11");
isParsable(Double.class, "11.11");
Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");
Run Code Online (Sandbox Code Playgroud)

这是我的代码完整的方法描述.

import java.lang.reflect.*;

/**
 * METHOD: isParsable<p><p>
 * 
 * This method will look through the methods of the specified <code>from</code> parameter
 * looking for a public method name starting with "parse" which has only one String
 * parameter.<p>
 * 
 * The <code>parser</code> parameter can be a class or an instantiated object, eg:
 * <code>Integer.class</code> or <code>new Integer(1)</code>. If you use a
 * <code>Class</code> type then only static methods are considered.<p>
 * 
 * When looping through potential methods, it first looks at the <code>Class</code> associated
 * with the <code>parser</code> parameter, then looks through the methods of the parent's class
 * followed by subsequent ancestors, using the first method that matches the criteria specified
 * above.<p>
 * 
 * This method will hide any normal parse exceptions, but throws any exceptions due to
 * programmatic errors, eg: NullPointerExceptions, etc. If you specify a <code>parser</code>
 * parameter which has no matching parse methods, a NoSuchMethodException will be thrown
 * embedded within a RuntimeException.<p><p>
 * 
 * Example:<br>
 * <code>isParsable(Boolean.class, "true");<br>
 * isParsable(Integer.class, "11");<br>
 * isParsable(Double.class, "11.11");<br>
 * Object dateFormater = new java.text.SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");<br>
 * isParsable(dateFormater, "2001.07.04 AD at 12:08:56 PDT");<br></code>
 * <p>
 * 
 * @param parser    The Class type or instantiated Object to find a parse method in.
 * @param str   The String you want to parse
 * 
 * @return true if a parse method was found and completed without exception
 * @throws java.lang.NoSuchMethodException If no such method is accessible 
 */
public static boolean isParsable(Object parser, String str) {
    Class theClass = (parser instanceof Class? (Class)parser: parser.getClass());
    boolean staticOnly = (parser == theClass), foundAtLeastOne = false;
    Method[] methods = theClass.getMethods();

    // Loop over methods
    for (int index = 0; index < methods.length; index++) {
        Method method = methods[index];

        // If method starts with parse, is public and has one String parameter.
        // If the parser parameter was a Class, then also ensure the method is static. 
        if(method.getName().startsWith("parse") &&
            (!staticOnly || Modifier.isStatic(method.getModifiers())) &&
            Modifier.isPublic(method.getModifiers()) &&
            method.getGenericParameterTypes().length == 1 &&
            method.getGenericParameterTypes()[0] == String.class)
        {
            try {
                foundAtLeastOne = true;
                method.invoke(parser, str);
                return true; // Successfully parsed without exception
            } catch (Exception exception) {
                // If invoke problem, try a different method
                /*if(!(exception instanceof IllegalArgumentException) &&
                   !(exception instanceof IllegalAccessException) &&
                   !(exception instanceof InvocationTargetException))
                        continue; // Look for other parse methods*/

                // Parse method refuses to parse, look for another different method
                continue; // Look for other parse methods
            }
        }
    }

    // No more accessible parse method could be found.
    if(foundAtLeastOne) return false;
    else throw new RuntimeException(new NoSuchMethodException());
}


/**
 * METHOD: willParse<p><p>
 * 
 * A convienence method which calls the isParseable method, but does not throw any exceptions
 * which could be thrown through programatic errors.<p>
 * 
 * Use of {@link #isParseable(Object, String) isParseable} is recommended for use so programatic
 * errors can be caught in development, unless the value of the <code>parser</code> parameter is
 * unpredictable, or normal programtic exceptions should be ignored.<p>
 * 
 * See {@link #isParseable(Object, String) isParseable} for full description of method
 * usability.<p>
 * 
 * @param parser    The Class type or instantiated Object to find a parse method in.
 * @param str   The String you want to parse
 * 
 * @return true if a parse method was found and completed without exception
 * @see #isParseable(Object, String) for full description of method usability 
 */
public static boolean willParse(Object parser, String str) {
    try {
        return isParsable(parser, str);
    } catch(Throwable exception) {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


lar*_*ars 5

一种表现良好的方法,避免尝试捕获和处理负数和科学记数法.

Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );

public static boolean isNumeric( String value ) 
{
    return value != null && PATTERN.matcher( value ).matches();
}
Run Code Online (Sandbox Code Playgroud)


use*_*153 5

要仅匹配仅包含ASCII数字的正十进制整数,请使用:

public static boolean isNumeric(String maybeNumeric) {
    return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
}
Run Code Online (Sandbox Code Playgroud)


Mea*_*all 5

这是我的类,用于检查字符串是否为数字.它还修复了数字字符串:

特征:

  1. 删除不必要的零["12.0000000" - >"12"]
  2. 删除不必要的零["12.0580000" - >"12.058"]
  3. 删除非数字字符["12.00sdfsdf00" - >"12"]
  4. 处理负字符串值["-12,020000" - >" - 12.02"]
  5. 删除多个点["-12.0.20.000" - >" - 12.02"]
  6. 没有额外的库,只有标准的Java

干得好...

public class NumUtils {
    /**
     * Transforms a string to an integer. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToInteger(String str) {
        String s = str;
        double d;
        d = Double.parseDouble(makeToDouble(s));
        int i = (int) (d + 0.5D);
        String retStr = String.valueOf(i);
        System.out.printf(retStr + "   ");
        return retStr;
    }

    /**
     * Transforms a string to an double. If no numerical chars returns a String "0".
     *
     * @param str
     * @return retStr
     */
    static String makeToDouble(String str) {

        Boolean dotWasFound = false;
        String orgStr = str;
        String retStr;
        int firstDotPos = 0;
        Boolean negative = false;

        //check if str is null
        if(str.length()==0){
            str="0";
        }

        //check if first sign is "-"
        if (str.charAt(0) == '-') {
            negative = true;
        }

        //check if str containg any number or else set the string to '0'
        if (!str.matches(".*\\d+.*")) {
            str = "0";
        }

        //Replace ',' with '.'  (for some european users who use the ',' as decimal separator)
        str = str.replaceAll(",", ".");
        str = str.replaceAll("[^\\d.]", "");

        //Removes the any second dots
        for (int i_char = 0; i_char < str.length(); i_char++) {
            if (str.charAt(i_char) == '.') {
                dotWasFound = true;
                firstDotPos = i_char;
                break;
            }
        }
        if (dotWasFound) {
            String befDot = str.substring(0, firstDotPos + 1);
            String aftDot = str.substring(firstDotPos + 1, str.length());
            aftDot = aftDot.replaceAll("\\.", "");
            str = befDot + aftDot;
        }

        //Removes zeros from the begining
        double uglyMethod = Double.parseDouble(str);
        str = String.valueOf(uglyMethod);

        //Removes the .0
        str = str.replaceAll("([0-9])\\.0+([^0-9]|$)", "$1$2");

        retStr = str;

        if (negative) {
            retStr = "-"+retStr;
        }

        return retStr;

    }

    static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

}
Run Code Online (Sandbox Code Playgroud)


Mad*_*ota 5

正则表达式匹配

这是另一个升级的"CraigTP"正则表达式与更多验证匹配的示例.

public static boolean isNumeric(String str)
{
    return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
}
Run Code Online (Sandbox Code Playgroud)
  1. -允许一个负号,必须在开头.
  2. 负号后必须有数字.
  3. .允许一个十进制符号.
  4. 十进制符号后必须有数字.

正则表达式测试

1                  --                   **VALID**
1.                 --                   INVALID
1..                --                   INVALID
1.1                --                   **VALID**
1.1.1              --                   INVALID

-1                 --                   **VALID**
--1                --                   INVALID
-1.                --                   INVALID
-1.1               --                   **VALID**
-1.1.1             --                   INVALID
Run Code Online (Sandbox Code Playgroud)


Chr*_*ell 5

例外是昂贵的,但在这种情况下,RegEx需要更长的时间.下面的代码显示了两个函数的简单测试 - 一个使用异常,一个使用正则表达式.在我的机器上,RegEx版本比异常慢10倍.

import java.util.Date;


public class IsNumeric {

public static boolean isNumericOne(String s) {
    return s.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.      
}

public static boolean isNumericTwo(String s) {
    try {
        Double.parseDouble(s);
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static void main(String [] args) {

    String test = "12345.F";

    long before = new Date().getTime();     
    for(int x=0;x<1000000;++x) {
        //isNumericTwo(test);
        isNumericOne(test);
    }
    long after = new Date().getTime();

    System.out.println(after-before);

}

}
Run Code Online (Sandbox Code Playgroud)


小智 5

//请检查以下代码

public static boolean isDigitsOnly(CharSequence str) {
    final int len = str.length();
    for (int i = 0; i < len; i++) {
        if (!Character.isDigit(str.charAt(i))) {
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)