Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!