aestheticsData
aestheticsData

Reputation: 747

regex for simple arithmetic expression

I've read other stackoverflow posts about a simple arithmetic expression regex, but none of them is working with my issue:

I need to validate this kind of expression: "12+5.6-3.51-1.06",

I tried

const mathre = /(\d+(.)?\d*)([+-])?(\d+(.)?\d*)*/;
console.log("12+5.6-3.51-1.06".match(mathre));

but the result is '12+5', and I can't figure why ?

Upvotes: 2

Views: 999

Answers (2)

MobDev
MobDev

Reputation: 1632

You would try to use this solution for PCRE compatible RegExp engine:

^(?:(-?\d+(?:[\.,]{1}\d)?)[+-]?)*(?1)$
  • ^ Start of String
  • (?: Non capture group ng1
  • (-?\d+(?:[\.,]{1}\d)?) Pattern for digit with or without start "-" and with "." or "," in the middle, matches 1 or 1.1 or 1,1 (Matching group 1)
  • [+-]? Pattern for "+" or "-"
  • )* Says that group ng1 might to repeat 0 or more times
  • (?1) Says that it must be a digit in the end of pattern by reference to the first subpattern
  • $ End of string

As JS does not support recursive reference, you may use full version instead:

/^(?:(-?\d+(?:[\.,]{1}\d)?)[+-]?)*(-?\d+(?:[\.,]{1}\d)?)$/gm

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163277

You only get 12.5 as a match, as there is not /g global flag, but if you would enable the global flag it will give partial matches as there are no anchors ^ and $ in the pattern validating the whole string.

The [+-] is only matched once, which should be repeated to match it multiple times.

Currently the pattern will match 1+2+3 but it will also match 1a1+2b2 as the dot is not escaped and can match any character (use \. to match it literally).

For starting with digits and optional decimal parts and repeating 1 or more times a + or -:

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

Regex demo

If the values can start with optional plus and minus and can also be decimals without leading digits:

^[+-]?\d*\.?\d+(?:[-+][+-]?\d*\.?\d+)+$
  • ^ Start of string
  • [+-]? Optional + or -
  • \d*\.\d+ Match *+ digits with optional . and 1+ digits
  • (?: Non capture group
    • [-+] Match a + or -
    • [+-]?\d*\.\d+ Match an optional + or - 0+ digits and optional . and 1+ digits
  • )+ Close the noncapture group and repeat 1+ times to match at least a single + or -
  • $ End of string

Regex demo

Upvotes: 3

Related Questions