Darw1n34
Darw1n34

Reputation: 19

Java - Regular Expression valid entry

I am trying to determine if variable degreeOfDifficulty a numeric value between "1.2" and "4.8" (inclusive), and to not accept character values. So "1.0", "4.9", "a", and "!" are invalid; "1.2", "4.8", "4.0", and "4" are valid. Thus far I have:

degreeOfDiffString.matches("^[1](\\.[2-9]?)?|^[2-3](\\.[0-9]?)?|[4](\\.[0-8]?)?"))

Is there something I am missing that makes an error throw if I enter a character?

Upvotes: 0

Views: 115

Answers (4)

syb0rg
syb0rg

Reputation: 8247

You don't need a regex for this. Just parse your degreeOfDiffString using Double.parseDouble(), and then check if the double is between 1.2 and 4.8 (inclusive).

Example (untested, just something I typed up now):

try
{
    String degreeOfDiffString = "3.4";
    double number = Double.parseDouble(degreeOfDiffString);
    if (number < 1.2 || number > 4.8) System.out.println("Invalid difficulty.");
    else
    {
        // Do stuff
    }
} catch (Exception e)
{
    // Handle exception
}

If there are random things in the String, such as "!" or some letter, then an NumberFormatException should be thrown, which you can deal with.

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

try with this pattern that match accepted numbers:

1\\.[2-9]|[23](\\.\\d)?|4(\\.[0-7])?|4\\.8

Upvotes: 0

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

The pattern isn't correct as it stands.

One quibble is that you use [1] and [4] when you really mean 1 and 4 respectively.

You must put only one ^ at the start of your pattern; the other carets are incorrect. Also, Java matches() method matches the entire pattern against the subject so the caret is redundant.

The way you have the decimal point match phrased, it will accept both a bare period after the first digit as well as a period followed by a digit. Is this what you want?

Upvotes: 0

srikanta
srikanta

Reputation: 2999

Don't use regex when you can avoid it. You can actually parse degreeOfDiffString and get the numeric value (if it is numeric) and then check for upper and lower bounds (1.2 to 4.8). Easier to code and understand what is going on. Regex makes your code error prone and if you decide to change the bounds later, you have to re-work your regex.

try
{
    double d = Double.parseDouble(degreeOfDiffString);
    if(d >= 1.2 && d <= 4.8)
    {
        return true; // valid
    }
}
catch(NumberFormatException ex)
{
}
return false; // all other cases -> invalid

Upvotes: 3

Related Questions