Find if the String is a number or floating point number - Regular Expression

Find if a string contains only digits?
   public static boolean stringContainsOnlyDigits(String s) {
        Pattern p = Pattern.compile( "^[0-9]+$" );
        Matcher m = p.matcher( s );
        return m.find();
    }

Find if the String is a Floating Point number.
   public static boolean stringIsFloatingPointNumber(String s) {
        Pattern p = Pattern.compile( "^[-+]?[0-9]*\\.?[0-9]+$" );
        Matcher m = p.matcher( s );
        boolean found = m.find();
        if(found) {
            System.out.println("found: " + m.group(0));
        }
        return found;
    }

The caveat here is the strings are long text and Double.parseDouble() will be out of range. Such problems can be solved only using Regular Expressions.

Comments

Popular posts from this blog

Print staircase with both base and height equal to n

Find the maximum occurring character in given String ?

Find the longest substring without repeating characters