0

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?

Community
  • 1
  • 1
  • 1
    Gracchus, if you haven't tried regex hero, you may want to give it a shot. It allows one to experiment with regex statements and test them with various data to no end. [RegexHero.net](http://regexhero.net). – STLDev Jun 14 '14 at 02:11
  • 1
    @Gracchus: http://regex101.com/ might help, then (works online, requires no installation) – Amal Murali Jun 14 '14 at 02:13
  • 1
    @Gracchus: If you're looking for an interactive tutorial, try http://regexone.com For a good reference, use this site: http://regular-expressions.info For a book, try Mastering Regular Expressions by Jeffrey Friedl. – Amal Murali Jun 14 '14 at 02:15

2 Answers2

1

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.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
1

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 .

No \d is actually \d*, which means that it will only enforce one [1-9] (preceded by none or many \ds). So

/-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?(?:[eE][+\-]?\d+)?/
/-?(?:0|[1-9]\d*)(?:\.\d*[1-9])?(?:[eE][+\-]?[1-9]\d*)?/ # no (leading) zero exponent

will work. It does however enforce one digit after the dot, if a decimal part is apparent.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375