Drago
Drago

Reputation: 1875

Spacing at last part of the regex

I've the following regex:

/(\(*)?(\d+)(\)*)?([+\-*\/^%]+)(\(*)?(\)*)?/g

I have the following string:

(5+4+8+5)+(5^2/(23%2))

I use the regex to add space between numbers, arithmetic operators and parentheses.

I do that like:

\1 \2 \3 \4 \5 \6

That turns the string into:

( 5 + 4 + 8 + 5 ) + ( 5 ^ 2 / ( 23 % 2))

As you can see the last two parentheses don't get spaced.

How can I make them space as well?

The output should look like:

( 5 + 4 + 8 + 5 ) + ( 5 ^ 2 / ( 23 % 2 ))

Try out the regex here.

Upvotes: 0

Views: 38

Answers (2)

user557597
user557597

Reputation:

You could try a simple and fast solution

edit
Some tips:
I know you are not validating the simple math expressions, but it would not hurt to do that before trying to beautify.

Either way you should remove all whitespace ahead of time
Find \s+ Replace nothing

To condense summation symbols you could do:
Find (?:--)+|\++ Replace +
Find [+-]*-+* Replace -

Division and power symbol meaning will vary with implementation,
and to condense them is not advisable, and better to just validate the form.

Validation is the more complex feat complicated by the meaning of parenthesis,
and their balance. That is another topic.

A minimum character validation should be done though.
String must be matched by ^[+\-*/^%()\d]+$ at least.


After optionally doing the above, run the beautifier on it.

https://regex101.com/r/NUj036/2

Find ((?:(?<=[+\-*/^%()])-)?\d+(?!\d)|[+\-*/^%()])(?!$))
Replace '$1 '

Explained

 (                             # (1 start)
      (?:                           # Allow negation if symbol is behind it
           (?<= [+\-*/^%()] )
           -
      )?
      \d+                           # Many digits
      (?! \d )                      #  - don't allow digits ahead
   |                              # or,
      [+\-*/^%()]                   # One of these operators
 )                             # (1 end)
 (?! $ )                       # Don't match if at end of string

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can try something like this based on word boundaries and on non-word characters:

\b(?!^|$)|\W\K(?=\W)

and replace with a space.

demo

details:

\b      # a word-boundary
(?!^|$) # not at the start or at the end of the string
|       # OR
\W      # a non-word character
\K      # remove characters on the left from the match result
(?=\W)  # followed by a non-word character

Upvotes: 1

Related Questions