-2

I'm trying to make a regex, that checks if something is a price. I'm not good at regular expressions and this one give me a regex syntax error. It should check if the input is something like 13.3 or 0.1 or .4 or 6 or 200 or 3.04, which could all be interpreted as a price. I tried using Double.valueOf(String), however, this method accepts strings like 3.00, so more than 2 floating points.

private boolean validateAndSet(JTextField tf) {
    boolean isDouble = true;
    try { 
        if (tf.getText().matches("^[0-1]*(\\.)?[0-1]{0-2}$"))   {
            item.setAlertPrice(Double.valueOf(tf.getText()));
            return true;
        }
        isDouble = false;
    } catch (NumberFormatException nfe) {
        isDouble = false;
    } finally {
        if (!isDouble) {
            System.out.println("Not a price;");
            tf.setText("0.00");
        }

    }
    return isDouble;
}

2 Answers2

1

Wrong things about your regex:

  1. [0-1] -> this delimites a 0 or a 1, you need to use \d to delimiter every number.
  2. {0-2} -> this isn't correct, you need to use , instead of -

The rest I think is okay.

Javier Diaz
  • 1,791
  • 1
  • 17
  • 25
0

Try "^[0-9]*?(\\.)?[0-9]{0,2}$", instead.

DWright
  • 9,258
  • 4
  • 36
  • 53
  • @Javier detected the same issue (not 0-1, but 0-9). Further, I think you need to make that * non-greedy as in my example. – DWright Dec 23 '12 at 18:28