Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex in java with conditions

Tags:

java

regex

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

like image 266
user1679321 Avatar asked Jan 30 '26 07:01

user1679321


1 Answers

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);
like image 93
Tim Pietzcker Avatar answered Feb 01 '26 22:02

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!