Search code examples
regexzeroscientific-notation

Invalidate scientific notation with 0 value exponent or trailing 0s


I am using this solution to regex scientific notation:

/-?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?/

I'd like to add a slight amount of space conservation, so I'd like to also forbid trailing zeros after the decimal point and zero value as the exponent.

I think that adding [1-9] after \.\d will enforce no trailing zeros, but I think it will also force at least two numbers after . which is undesirable.

I do not possess the necessary experience to modify this regex properly.

How can my intent be implemented?


Solution

  • You can make this simple change:

    /-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?(?:[eE][+-]?[1-9]\d*)?/
    

    Note that [1-9]\d* will forbid exponants with a leading zero.