I'm trying to create a regex that will accept the following values:
I came up with ([0-9]){0,2}\.([0-9]){0,2}
which to me says "the digits 0 through 9 occurring 0 to 2 times, followed by a '.' character (which should be optional), followed by the digits 0 through 9 occuring 0 to 2 times. If only 2 digits are entered the '.' is not necessary. What's wrong with this regex?
(?:...) A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
You didn't make the dot optional:
[0-9]{0,2}(\.[0-9]{1,2})?
First off, {0-2}
should be {0,2}
as it was in the first instance.
Secondly, you need to group the repetition sections as well.
Thirdly, you need to make the whole last part optional. Because if there's a dot, there must be something after it, you should also change the second repetition thing to {1,2}
.
([0-9]{0,2})(\.([0-9]{1,2}))?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With