Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

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

I'm trying to check that a numeric value has a specific amount of digits.

  1. there shouldn't be more than 19 digits overall
  2. there shouldn't be more than 17 digits before the decimal point (integer part)
  3. there shouldn't be more than 4 digits after the decimal point (fractional part)
  4. there can be a decimal point or not
  5. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use A(?=.*d)(?!(?:D*d){20,})[+-]?d{0,17}(?:.d{1,4})?z. Remember to use double backslashes when using it in java code.

  • A - matches start of string
  • (?=.*d) check that there is at least one digit (because of basically everythin being optional)
  • (?!(?:D*d){20,}) check that there are no more than 19 digits
  • [+-]? match optional + or -
  • d{0,17} match up to 17 digits integer part
  • (?:.d{1,4})? match up to 4 digits in the decimal part, you can use {0,4} if 12. is valid
  • z match end of the string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...