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



我有以下正则表达式:

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

我有以下字符串:

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

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

我这样做是这样的:

1 2 3 4 5 6

这会将字符串转换为:

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

如您所见,最后两个括号没有间隔。

我怎样才能让它们也腾出空间?

输出应如下所示:

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

在这里尝试正则表达式。

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

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

无论哪种方式,您都应该提前
remove all whitespace查找s+替换nothing

要压缩求和符号,您可以执行以下操作:
查找(?:--)+|++替换+
查找[+-]*-+*替换-

划分和权力符号的含义会随着实施而变化,并且不建议将它们压缩,
最好只是验证形式。

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

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


选择性地执行上述操作后,在其上运行美化器。

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

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

解释

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

您可以根据单词边界和非单词字符尝试类似的东西:

b(?!^|$)|WK(?=W)

并替换为空格。

演示

详:

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

最新更新