I have the following method:
protected BigDecimal stringToBigDecimal(String value) throws ParseException
{
if (Pattern.matches("[\\d,.]+", value))
{
Number n = NumberFormat.getInstance().parse(value);
return new BigDecimal(n.doubleValue());
}
else
{
throw new ParseException("Invalid String", -1);
}
}
This value throws an exception (as expected), so this regExpr works:
String wrongAmount = "1,U35,345.43";
But when I try this:
protected BigDecimal stringToBigDecimal(String value) throws ParseException
{
if (Pattern.matches("[\\D&&[^.,]]+", value))
{
throw new ParseException("Invalid String", -1);
}
Number n = NumberFormat.getInstance().parse(value);
return new BigDecimal(n.doubleValue());
}
No exception is thrown, but why?
First I thought that there is a logical problem with the “except for” expression so I tried this value with this pattern:
String wrongAmount = "1U3534543";
protected BigDecimal stringToBigDecimal(String value) throws ParseException
{
if (Pattern.matches("[\\D]+", value))
{
throw new ParseException("Invalid String", -1);
}
Number n = NumberFormat.getInstance().parse(value);
return new BigDecimal(n.doubleValue());
}
…but this doesn’t match? What did I understand wrong on the “non-digit expression” \\D.. The value contains an “U”, so why doesn’t it match?
You are not properly negating you expressions.
In the first example, you say “if my input matches only digits, commas and dots”, then it’s ok.
In your second example (and I am not sure that it does what you meant but that’s another story), you meant to say “if the input matches only non-digits, non-commas, non-dots chars”, but your input contains digits, so the match won’t work.
In your last example, same thing, you are saying “if the input matches only non-digit chars” but again you have digits in your input