0

The regex must match all the positive doubles with maximum of two digits after decimal point, numbers greater than 0.01 AND also the scientific notation e.g. (1.0E7).

I managed to solve these two problems separately.

For matching all positive doubles with maximum of 2 digits after decimal point and numbers greater than 0.01:

"^(?!0+\\.0+$)^\\d+(?:\\.\\d{1,2})?$"

For any numbers including scientific notation:

"^[+-]?\\d+(?:\\.\\d*(?:[eE][+-]?\\d+)?)?$"

The problem comes when I want to put them together into only one.

I tried the methods described here but none worked for me. JavaScript/AngularJS is the language used if it has any importance.

Any suggestions?

Community
  • 1
  • 1
Leo Messi
  • 5,157
  • 14
  • 63
  • 125

2 Answers2

1

Try:

  • strip ^$
  • enclose each originary regex into a non capturing group
  • 'OR' the two groups
  • enclose the whole into a non capturing group
  • re-add ^ $ to the entire expression.

Result:

^(?:(?:(?!0+\\.0+$)^\\d+(?:\\.\\d{1,2})?)|(?:[+-]?\\d+(?:\\.\\d*(?:[eE][+-]?\\d+)?)?))$
Attersson
  • 4,755
  • 1
  • 15
  • 29
  • I tried your method but it does not have the wanted behavior. I can introduce more than 2 digits after decimal points and also negative values and they make the match. Isn't the combination of two regex going to act like a intersection between those two? Or is a better way to do it? – Leo Messi Jun 04 '18 at 13:47
  • I want to not be able to introduce more than 2 digits :) The regex should match all positive doubles with maximum of two digits after decimal point, numbers greater than 0.01 AND also the scientific notation e.g. (1.0E7) in the same time – Leo Messi Jun 04 '18 at 13:51
  • You might want to keep the regexes separate. Since they work line by line, try to match with one regex, then try the other. Anyway it's weird. That should have worked. Try posting an example on regex101 – Attersson Jun 04 '18 at 13:53
  • now I'm using a switch with cases and for each case there is a return. e.g.: `return "^(...)$"`, I don't know if there is a way to add multiple checks here... – Leo Messi Jun 04 '18 at 13:56
  • 1
    The problem is the second expression matches already numbers like 55.555. My method works. Example of second expression: https://regex101.com/r/5bFRDQ/1/ – Attersson Jun 04 '18 at 14:12
0

You can separate your regex into blocks

(^(?!0+\\.0+$)^\\d+(?:\\.\\d{1,2}))?$ ?(^[+-]?\\d+(?:\\.\\d*(?:[eE][+-]?\\d+)?)?$)