Question

I am writing parser and I need to catch "numbers" but avoid chars such as [-+] before "e".
My problem is that pattern marks "-" or "+" right after my mantissa but it should not.

I use this pattern:
/^[.0-9]+[-+e.0-9]*$/g

//Test strings:
//wrong string - match - PROBLEM, but should not be because of '-' or '+' after mantissa
1.2-
2.3-e
1.2+
1.2+e
//wrong string - does not match - OK
-123
1.2b+3
+123
-123-e9
//right string - match - OK
1
1.
1.2
123.5
.2
1.2.
.2.
1e3
.e3
1.e3
1.2e3
1.2e+3
1.2e-3
1.2e3.
1.2e3.4
1.2e-399
1.2e+e3

String marked as 'wrong' should NOT be catch.
These strings will be split into table like this but in another module.
I just want to avoid them to be catch by my patern.
1.2- // ['1.2','-']
2.3-e // ['2.3','-','e']
1.2+ // ['1.2','+']
1.2+e // ['1.2','+','e']

Do you have idea how to improve my pattern or it should be write differently?
TEST ^[.0-9]+[-+e.0-9]*$
SOLVED ^\.?\d*(\.(\d+)?)?((?:e[+-]?|[+-]e)*\d+(\.\d+)?)?\.?$

Was it helpful?

Solution

I've tweaked a little bit a solution I did for the regex101 quiz and I came up with this solution: DEMO

^[.,]?(\d)*([.,](\d+)?)?((?:e[+-]?|[+-]e)*\d+(\.\d+)?)?\.?$

EDIT: A secon approach since the explanation of the question wasn't clear.

Final answer edited and accepted: ^\.?\d*(\.(\d+)?)?((?:e[+-]?|[+-]e)*\d+(\.\d+)?)?\.?$

OTHER TIPS

How about this, it matches more, but not everything because I wasn't entirely sure about your "rules" (e.g. when are multiple . okay? why is 1b+1 okay? why is e+e or 1-e okay?)

/^[+-]?(?:\d*\.\d+|\d+\.\d*|\d+)(?:e[+-]?(?:\d*\.\d+|\d+\.\d*|\d+))?$/g

Graphic by debuggex.com

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top