Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regex that will parse 00.00

Tags:

regex

I'm trying to create a regex that will accept the following values:

  • (blank)
  • 0
  • 00
  • 00.0
  • 00.00

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?

like image 689
James Cadd Avatar asked Aug 06 '09 13:08

James Cadd


People also ask

What does (?: Mean in 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.

What does regex 0 * 1 * 0 * 1 * Mean?

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.

What does * do in regex?

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.

Can regex be used for numbers?

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.


2 Answers

You didn't make the dot optional:

[0-9]{0,2}(\.[0-9]{1,2})?
like image 154
Joachim Sauer Avatar answered Sep 20 '22 12:09

Joachim Sauer


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}))?
like image 45
Samir Talwar Avatar answered Sep 21 '22 12:09

Samir Talwar