Skip to content Skip to sidebar Skip to footer

How To Create Regex For 00.00?

I want to create a regex which validate the all below conditions. Only numeric [0-9] value allow. 00.00 0.00 00.0 0.0 00 0

Solution 1:

Per comment of OP/modified question, if you want 1 or 2 digits, optionally followed by (a period, followed by 1 or 2 more digits), you could use this regex:

var regex = /^\d{1,2}(\.\d{1,2})?$/;
// The ( ) groups several things together sequentially.// The ? makes it optional.

If you want 1 or 2 digits, followed by a period, followed by 1 or 2 more digits:

var regex = /^\d{1,2}\.\d{1,2}$/;
// The / denotes the start and end of the regex.// The ^ denotes the start of the string.// The $ denotes the end of the string.// The \d denotes the class of digit characters.// The {1,2} denotes to match 1 to 2 occurrences of what was encountered immediately to the left.// The \. denotes to match an actual . character; normally . by itself is a wildcard.// happy paths
regex.test('00.00'); // true
regex.test('0.00'); // true
regex.test('00.0'); // true
regex.test('0.0'); // true
regex.test('12.34'); // true (test other digits than '0')// first half malformed
regex.test('a0.00'); // non-digit in first half
regex.test('.00'); // missing first digit
regex.test('000.00'); // too many digits in first half// period malformed
regex.test('0000'); // missing period
regex.test('00..00'); // extra period// second half malformed
regex.test('00.a0'); // non-digit in second half
regex.test('00.'); // missing last digit
regex.test('00.000'); // too many digits in second half

Solution 2:

To match 1 or more zeros on both sides of the dot you may use the + operator. And because the dot has a special meaning you'll have to quote it. 0+\.0+ should do that job.

To match any digit you may use \d+\.\d+...

And to limit it to max 2 digits use \d{1,2}\.\d{1,2}.

Post a Comment for "How To Create Regex For 00.00?"