I am trying to create a regex which meets the following:
One or two or three decimal number.
No leading zeros inside the decimal number.
Precision 2.
Proper Fractions are allowed (0.__ numbers).
No text before the decimal number
Regex should match the following:
The regex should not match the following:
I came up with the following regex:
(?<!.)^([1-9][0-9]{0,2}\.[0-9][0-9])$
It meets all of the above except fractions.
I don't want leading zeros in case the decimal number has 2 or 3 digits. However, in case it`s proper fraction, I do want 0.__ to be allowed).
However, my regex does not match "0.__" decimal numbers because it expects the number to start with 1 due to " ^[1-9]
".
Please advise how can I modify my regex to match also "0.__" numbers.
What about this:
\b(0|[1-9]\d{0,2})\.\d{2}\b
Here you can see that it matches exactly what you want.
You can use this regex:
^(?!0+[1-9])\d{1,3}\.\d{2}$
(?!0+[1-9])
is a negative lookahead that will stop leading zeroes in the number.
Assuming you're using re.match, here's the shortest you can use:
(?!0)\d{1,3}\.\d{2}
If you are using search:
^(?!0)\d{1,3}\.\d{2}$
You don't need to treat the first number differently, so you can use \\d (which is the same as [0-9]) and make sure the first character is not 0 with a negative lookahead (?!0).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.