I'm trying to check that a numeric value has a specific amount of digits.
- there shouldn't be more than 19 digits overall
- there shouldn't be more than 17 digits before the decimal point (integer part)
- there shouldn't be more than 4 digits after the decimal point (fractional part)
- there can be a decimal point or not
- there can be a preceding + or - or not
valid examples:
- 1
- 1.0
- .0
- 12345678901234567.12
- +12345678901234567.12
- -12345678901234567.12
- 123456789012345.1234
- +123456789012345.1234
- -123456789012345.1234
invalid examples
- 1234567890123456.1234 //because there are 20 digits
- 123456789012345678.1 //because there are more than 17 digits before the decimal point
- 1.12345 //because there are more than 4 digits after the decimal point
I have tried the examples from this tutorial but can't get them to work how I'd like to. I think I have troubles understanding how to use look aheads/arounds since this part won't really do what I'd like it to:
@Test
public void testTutorialCode() {
//min two, max four digits for the whole expression
Pattern p = Pattern.compile("\A(?=(?:[^0-9]*[0-9]){2,4})\z");
assertFalse(p.matcher("+1234.0").matches());
assertTrue(p.matcher("12").matches());
assertTrue(p.matcher("12.12").matches());
assertTrue(p.matcher("+123.0").matches());
assertFalse(p.matcher("1234.0").matches());
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…