arynaq
arynaq

Reputation: 6870

Regex, excluding non-number

In my program I read input from the console and determine whether it is a number or not. Numbers can be any decimal +-. For instance having 123.18p18 is not allowed since there is a nondigit in there, same with -123.18p18. The bad way of doing this (which I am currently doing) is checking if it is a double and catching exceptions, but since I am just parsing a string I think regex is far better to use here. This is my first day in its use (regex) and it seems like an alien language.

I came up with ".*\\D+.*" but that only handles positive numbers.

Edit: Integers are also acceptable.

Upvotes: 0

Views: 133

Answers (4)

AlanFoster
AlanFoster

Reputation: 8306

The following regex might work for you;

It defines a pattern which starts with either a + or - followed by zero or more digits and if there is a decimal point, then it must be followed by at least one digit

"^[+-]?\\d+(?:\\.?\\d+)$"

Upvotes: 1

naitoon
naitoon

Reputation: 665

To solve your initial problem, you can use the java.util.Scanner class. It provides methods for testing whether the next input is an integer, double, etc., or even testing whether the next input conforms to a given regular expression.

import java.util.Scanner;
//...
Scanner s = new Scanner(System.in);

while ( s.hasNext() ) {
    if ( s.hasNextInt() ) {
        int i = s.readInt();
        // Some work.
    } else if ( s.hasNextDouble() ) {
        double d = s.nextDouble();
        // Some work.
    } else if ( s.hasNext(regex) ) {
        String t = s.next(regex);
        // Some work.
    }
    // etc.
}

Upvotes: 2

hd1
hd1

Reputation: 34657

Try double doubleInstance = Double.parseDouble(string); and proceed...

Upvotes: 0

jlordo
jlordo

Reputation: 37813

You are looking for:

"^[+-]?\\d+([.]\\d+)?$"

Optional plus or minus in the beginning, followed by at least one digit. Before the end of the string there can optionally be one dot followed by at least one digit.

Upvotes: 2

Related Questions