cl332
cl332

Reputation: 33

Regex for matching up to a total of x digits where of those x digits, at most y can be after the decimal

I'm currently writing a validator where I need to check the formats of floats. My code reads in a format of (x,y) where x is the total possible digits in the float and y is the maximum digits out of x that can be after the decimal point. Apologies if this question has already been answered before, but I wasn't able to find anything similar.

For example, given a format of (5,3):

Valid values

55555
555.33
55.333
5555.3
.333

Invalid values

55555.5
555555
5.5555
.55555

This is my first time working with regex so if you guys have any tutorials that you recommend, please send it my way!

Upvotes: 2

Views: 48

Answers (2)

Aftab Khan
Aftab Khan

Reputation: 3923

Assuming JS you can try

function validate(value, total, dec) {
  let totalRegex = new RegExp(`\\d{0,${total}}$`);
  let decimalRegex = new RegExp(`\\.\\d{0,${dec}}$`);
  return totalRegex.test(value.replace(".","")) && (!(/\./.test(value)) || decimalRegex.test(value));
}

console.log(validate("555.55", 5, 2));
console.log(validate("55.555", 5, 2));
console.log(validate("5.5", 5, 2));
console.log(validate("55555", 5, 2));
console.log(validate("5.5555", 5, 2));

Upvotes: 1

Sebastian Proske
Sebastian Proske

Reputation: 8413

You can use a lookahead to ensure both conditions, like

^(?=(?:\.?\d){1,5}$)\d*(?:\.\d{1,3})?$
  • ^ match from the start of the string
  • (?=(?:\.?\d){1,5}$) check for the presence of 1 up to 5 digits to the end of the string - not caring to much about the correct number of dots
  • \d* match any number of digits
  • (?:\.\d{1,3})? match up to 3 decimal places
  • $ ensure end of the string

See https://regex101.com/r/lrP56w/1

Upvotes: 3

Related Questions