我需要在类似 lisp 的代码中替换括号之间所有不必要的空格,如下所示:
(print (number->string ( (func? '+ '-) 12 13 14 15) ) )
这样就变成了:
(display (number->string ((func? '+ '-) 12 13 14 15)))
我知道乍一看它看起来很简单,但它真的很棘手(至少对我来说)。这
是我尝试过的:
In [14]: re.sub(r"\)[ \t]*\)","))",")) ) ",0)
Out[14]: ')) ) '
In [15]: re.sub(r"\)[ \t]*\)","))",") ) ",0)
Out[15]: ')) '
In [16]: re.sub(r"\)[ \t]+\)","))",")) ) ",0)
Out[16]: '))) '
In [17]: re.sub(r"\)[ \t]+\)","))",")) ) ",0)
Out[17]: '))) '
In [18]: re.sub(r"\)[ \t]+\)","))",") ) ) ",0)
Out[18]: ')) ) '
In [19]: re.sub(r"\)[ \t]+\)","))",") ) ) ",1)
Out[19]: ')) ) '
In [20]: re.sub(r"\)[ \t]+\)","))",") ) ) ",0)
Out[20]: ')) ) '
In [21]: re.sub(r"\)[ \t]+\)","))",") ) ) ",0,re.M)
Out[21]: ')) ) '
In [22]: re.sub(r"\).+\)","))",") ) ) ",0,re.M)
Out[22]: ')) '
In [23]: re.sub(r"\)\s+\)","))",") ) ) ",0,re.M)
Out[23]: ')) ) '
In [24]: re.sub(r"\)([ \t]*)\)","))",") ) ",0)
Out[24]: ')) '
In [25]: re.sub(r"\)([ \t]*)\)","",") ) ",0)
Out[25]: ' '
In [26]: re.sub("\)([ \t]*)\)","))",") ) ",0)
Out[26]: ')) '
In [27]: re.sub("\)([ \t]*)\)","))",") ) )",0)
Out[27]: ')) )'
In [28]: re.sub("\)([ \t]*)\)","))",") ) )",0)
Out[28]: ')) )'
In [29]: re.sub("\)([ \t]*?)\)","))",") ) )",0)
Out[29]: ')) )'
In [30]: re.sub("\)(.+?)\)","))",") ) )",0)
Out[30]: ')) )'
在上述每种情况下,re.sub
仅替换第一个括号之间的空格,并将字符串的其余部分保留与以前相同的方式。我需要一个正则表达式来替换所有空格。