java - How to limit the number of digits before/after/ a decimal point and also overall with regex? -


i'm trying check numeric value has specific amount of digits.

  1. there shouldn't more 19 digits overall
  2. there shouldn't more 17 digits before decimal point (integer part)
  3. there shouldn't more 4 digits after decimal point (fractional part)
  4. there can decimal point or not
  5. there can 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 20 digits
  • 123456789012345678.1 //because there more 17 digits before decimal point
  • 1.12345 //because there more 4 digits after decimal point

i have tried examples this tutorial can't them work how i'd to. think have troubles understanding how use aheads/arounds since part won't i'd to:

@test public void testtutorialcode() {     //min two, max 4 digits 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()); } 

you can use \a(?=.*\d)(?!(?:\d*\d){20,})[+-]?\d{0,17}(?:\.\d{1,4})?\z. remember use double backslashes when using in java code.

  • \a - matches start of string
  • (?=.*\d) check there @ least 1 digit (because of everythin being optional)
  • (?!(?:\d*\d){20,}) check there no more 19 digits
  • [+-]? match optional + or -
  • \d{0,17} match 17 digits integer part
  • (?:\.\d{1,4})? match 4 digits in decimal part, can use {0,4} if 12. valid
  • \z match end of string

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -