Regex of max 5 decimal separate by +

Viewed 54

i'm trying to make a regex to add to a input pattern (HTML) to check if is valid, it need to be valid only if the input contain a string composed by decimal(with 1 or 2 number after comma) or integer number separated by a + and maximum of 5 number and it can not start or end with a + or it can not be possible to have a number with comma without number after (i use comma instead of dot for decimal)

for example

  • 10+5,1+6,20 OK
  • 10 OK
  • 6+4+8,9+3+9+3 NO
  • 10,2+4+6+ NO
  • 10,+5 NO

i've tried with something like this but id doesn't work very well

((\d{1,3}|(\d*,\d{1,2})*)+(\+)?){1,5}

also i've tried with this:

^((\s*)|([0-9]\d{0,9}(\,\d{1,2})?%?))*(\+((\s*)|([0-9]\d{0,9}(\,\d{1,2})?%?))+){0,4}$

but it doesn't work very well with the 2 digit max for the decimal and ending +

any suggestions ??

i've made some test here: https://regexr.com/5jsfv

it should pass the first 3 and faile on the last 4

thanks

1 Answers

You can use

^\d+(?:,\d{1,2})?(?:\+\d+(?:,\d{1,2})?){0,4}$

In the HTML pattern attribute use it as

pattern="\d+(?:,\d{1,2})?(?:\+\d+(?:,\d{1,2})?){0,4}"

See the regex demo.

NOTE: If you want to limit the number of digits in the integer part to be max 3, replace the \d+ with \d{1,3}:

^\d{1,3}(?:,\d{1,2})?(?:\+\d{1,3}(?:,\d{1,2})?){0,4}$

Details:

  • ^ - start of string (implicit in pattern regex)
  • \d+(?:,\d{1,2})? - one or more digits and then an optional sequence of a , and one or two digits
  • (?:\+\d+(?:,\d{1,2})?){0,4} - zero to four occurrences of a + char followed with one or more digits and then an optional sequence of a , and one or two digits
  • $ - end of string (implicit in pattern regex)
Related