正则表达式最后一部分的间距

Spacing at last part of the regex

我有以下正则表达式:

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

我有以下字符串:

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

我使用正则表达式在数字、算术运算符和括号之间添加 space。

我喜欢这样做:

将字符串变成:

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

如您所见,最后两个括号没有得到 spaced。

我怎样才能让它们也space?

输出应如下所示:

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

试试正则表达式 here

您可以尝试基于单词边界和非单词字符的类似方法:

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

并替换为 space。

demo

详情:

\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

您可以尝试一个简单快速的解决方案

编辑
一些提示:
我知道您没有验证简单的数学表达式,但是在尝试美化之前这样做并没有什么坏处。

无论如何你都应该remove all whitespace提前
查找 \s+ 替换 nothing

要压缩求和符号,您可以这样做:
查找 (?:--)+|\++ 替换 +
查找 [+-]*-+* 替换 -

除法和幂符号的含义会因实施而异,
压缩它们是不可取的,最好只验证表单。

验证是更复杂的壮举,括号的含义复杂化,
和他们的平衡。那是另一个话题。

不过应该进行最少的字符验证。
字符串必须至少匹配 ^[+\-*/^%()\d]+$


选择性地做完上面的事情后,运行美化就可以了。

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

查找((?:(?<=[+\-*/^%()])-)?\d+(?!\d)|[+\-*/^%()])(?!$))
替换 ' '

已解释

 (                             # (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