Java Regex Number Validate parseNumber(String input)

Here you can find the source of parseNumber(String input)

Description

parse Number

License

Open Source License

Declaration

public static int parseNumber(String input) throws NumberFormatException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.regex.Pattern;

public class Main {
    private static Pattern onlyNums = Pattern.compile("[^0-9]");
    private static Pattern containsNums = Pattern.compile(".*\\d.*");

    /**// w  w  w  .ja  v  a2  s. c  o  m
     * Returns a default value instead of a NumberFormatException when input is invalid
     *
     * @return matched number
     */
    public static int parseNumber(String input, int defaultReturn) {
        int num = defaultReturn;
        if (containsNumbers(input)) {
            input = stripNumber(input);
            num = Integer.parseInt(input);
        }
        return num;
    }

    public static int parseNumber(String input) throws NumberFormatException {
        int num;
        if (containsNumbers(input)) {
            input = stripNumber(input);
            num = Integer.parseInt(input);
        } else
            throw new NumberFormatException("Not a readable number \"" + input + "\"");
        return num;
    }

    public static boolean containsNumbers(String str) {
        return containsNums.matcher(str).matches();
    }

    public static String stripNumber(String input) {
        return onlyNums.matcher(input).replaceAll("");
    }
}

Related

  1. isNumeric(String value)
  2. isNumericAndCanNull(String src)
  3. isNumericAndCanNull(String src)
  4. isNumString(String txt)
  5. parseNumber(String in)
  6. parseNumber(String input)
  7. parseNumber(String s)
  8. parseNumbers(String str)