2

I have to write Regex in Java according to the following conditions:

  • total digit character limit = 64
  • a single digit of 0 is acceptable
  • first digit must be 1 through 9 if more than one digit
  • following digits can be 0 through 9
  • two digits are allowed after a decimal point
  • comma's are not accepted

so far I have only got this:

(\\d{1,64})

Can someone help me

0

2 Answers 2

8
Pattern regex = Pattern.compile(
    "^             # Start of string                 \n" +
    "(?!.{65})     # Assert length not 65 or greater \n" +
    "(?:           # Match either                    \n" +
    " 0            #  0                              \n" +
    "|             # or                              \n" +
    " [1-9]\\d*    #  1-n, no leading zeroes         \n" +
    ")             # End of alternation              \n" +
    "(?:           # Match...                        \n" +
    " \\.          #  a dot                          \n" +
    " \\d{2}       #  followed by exactly 2 digits   \n" +
    ")?            # ...optionally                   \n" +
    "$             # End of string", 
    Pattern.COMMENTS);
Sign up to request clarification or add additional context in comments.

Comments

1

Might be the most legible if you split it up into 4 scenarios:

(0(\.\d{1,2})?|[1-9](\d{0,63}|\d{0,61}\.\d|\d{0,60}\.\d\d))

That's a 0 optionally followed by a decimal and one or two more digits, or a 1-9 followed by one of:

  • up to 63 more digits
  • up to 61 more digits, a decimal, and one more digit
  • up to 60 more digits, a decimal, and two more digits

Definitely worth adding some comments inline with the Java regex, but I'm not too savvy with Java's regex syntax so I'll leave that as an exercise for the reader.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.