user1679321
user1679321

Reputation: 31

regex in java with conditions

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

so far I have only got this:

(\\d{1,64})

Can someone help me

Upvotes: 2

Views: 168

Answers (2)

Mu Mind
Mu Mind

Reputation: 11214

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.

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336448

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);

Upvotes: 8

Related Questions