-1

I have a string containing numbers and operator symbols for example like this: 99*8998+-999 I need to have a space between an operator and adjacent digit like this: 99 * 8998 +- 999

I tried JavaScript replaceAll with regex: /(\d+)([/*+-]+)(\d*)/g But this regex works fine until there are no non adjacent operator symbols in the string.

For example refer following working and non working conditions.

"998998+999".replaceAll(/(\d+)([/*+-]+)(\d*)/g, "$1 $2 $3")  
=> "998998 + 999" // Works as expected

"998998+-999".replaceAll(/(\d+)([/*+-]+)(\d*)/g, "$1 $2 $3") 
=> "998998 +- 999" // Works as expected

"99*8998+-999".replaceAll(/(\d+)([/*+-]+)(\d*)/g, "$1 $2 $3") 
=> "99 * 8998+-999" // Does not works as expected. Expected: "99 * 8998 +- 999"

The regex seems to return after first match without capturing next one even with the global flag.

What could be wrong?

Abhinandan Khilari
  • 947
  • 3
  • 11
  • 26

1 Answers1

2

Reason why your approach didn't work because your regex is matching and consuming characters in expression such as: 12+34-1 which has a overlapping match. Due to that you will have to use zero-width lookahead which will do only lookahead but won't consume characters from input.

You may match using this regex:

/(\d)(\+-|[\/*+-])(?=\d)/g

Replace using "$1 $2 "

RegEx Demo

There might be other 2 character operators for your case. I have used only +- in my example above. You can add then in alternations in 2nd capture group above.

RegEx Details:

  • (\d): Match and capture a digit in group #1
  • (\+-|[\/*+-]): Match +- or a single character operator /, *, + or -
  • (?=\d): Positive lookahead to assert that there is a digit ahead
anubhava
  • 761,203
  • 64
  • 569
  • 643