Home > front end >  Regex for number without leading or ending zeros
Regex for number without leading or ending zeros

Time:08-06

I am really struggling to find a regex that validates the following patterns.

Examples of patterns that should be valid:

An integer number:

25
100
0

A decimal number:

15.31
0.123
25.01

A number or decimal number followed by slash and another number or decimal number:

25/25
0/0
25.2/25.2
0.123/0.123
25.5/25 (decimal and integer combined)

A number or decimal number followed by slash and percentage symbol and another number or decimal number and percentage symbol:

25%/25%
0.125%/0.125%

The following patterns should be invalid:

0000 (more than one zero)
0.0
25%/25 (only one percentage symbol)
25//25 (two bar symbols)
25.00 (ending with zeros in the decimal part)
25.0500 (again ending with zeros in the decimal part)
02 (starting with a zero)

The following patterns are valid, but my regex is not accepting:

0.2%/0.1%
0.123/0.123

Could someone help me with this, and if possible with an explanation of the regex?

Current regex:

/^([1-9]\d*%?\/?|[1-9]\d*\.{1}[0-9]*[1-9]?[0-9]*[1-9]%?|^0\.[0-9]*[1-9]?[0-9]*[1-9])(\/([1-9]\d*%?\/?|[1-9]\d*\.{1}[0-9]*[1-9]?[0-9]*[1-9]%?|^0\.[0-9]*[1-9]?[0-9]*[1-9]))*$|^0{1}$/gm

Regex link: https://regex101.com/r/NtQpEB/1

CodePudding user response:

You may use this regex to match all of your cases:

^(?:[1-9]\d*|0)(?:\.(?:0*[1-9]) )?(%?)(?:/(?:[1-9]\d*|0)(?:\.(?:0*[1-9]) )?\1)?$

Updated RegEx Demo

RegEx Details:

  • ^: Start
  • (?:[1-9]\d*|0): Match a 0 or digits starting with 1-9
  • (?:\.(?:0*[1-9]) )?: Optional part after . that uses (?:0*[1-9]) to makes sure that it doesn't end with a zero
  • (%?): Match optional % and capture in group #1
  • (?:/(?:[1-9]\d*|0)(?:\.(?:0*[1-9]) )?\1)?: Optional part that comes after matching /. Note that we use \1 as back-reference here to make sure if % has been matched before / then it should be matched in 2nd part as well
  • $: End
  • Related