How to check if a String is numeric in Java

前端 未结 30 2511
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

相关标签:
30条回答
  • 2020-11-21 05:57

    With Apache Commons Lang 3.5 and above: NumberUtils.isCreatable or StringUtils.isNumeric.

    With Apache Commons Lang 3.4 and below: NumberUtils.isNumber or StringUtils.isNumeric.

    You can also use StringUtils.isNumericSpace which returns true for empty strings and ignores internal spaces in the string. Another way is to use NumberUtils.isParsable which basically checks the number is parsable according to Java. (The linked javadocs contain detailed examples for each method.)

    0 讨论(0)
  • 2020-11-21 05:58

    Here was my answer to the problem.

    A catch all convenience method which you can use to parse any String with any type of parser: isParsable(Object parser, String str). The parser can be a Class or an object. This will also allows you to use custom parsers you've written and should work for ever scenario, eg:

    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");
    

    Here's my code complete with method descriptions.

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:58

    Regex Matching

    Here is another example upgraded "CraigTP" regex matching with more validations.

    public static boolean isNumeric(String str)
    {
        return str.matches("^(?:(?:\\-{1})?\\d+(?:\\.{1}\\d+)?)$");
    }
    
    1. Only one negative sign - allowed and must be in beginning.
    2. After negative sign there must be digit.
    3. Only one decimal sign . allowed.
    4. After decimal sign there must be digit.

    Regex Test

    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
    
    0 讨论(0)
  • 2020-11-21 05:59

    A well-performing approach avoiding try-catch and handling negative numbers and scientific notation.

    Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)(\\.\\d+)?(E\\d+)?$" );
    
    public static boolean isNumeric( String value ) 
    {
        return value != null && PATTERN.matcher( value ).matches();
    }
    
    0 讨论(0)
  • 2020-11-21 05:59

    Parse it (i.e. with Integer#parseInt ) and simply catch the exception. =)

    To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.

    If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.

    0 讨论(0)
  • 2020-11-21 06:00

    To match only positive base-ten integers, that contains only ASCII digits, use:

    public static boolean isNumeric(String maybeNumeric) {
        return maybeNumeric != null && maybeNumeric.matches("[0-9]+");
    }
    
    0 讨论(0)
提交回复
热议问题