Search code examples
angularjsregexnumbersscientific-notation

Combine two regex expressions into one


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?


Solution

  • 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+)?)?))$