Reputation: 31
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
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:
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
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