[英]Replace two different characters with Regex
I want to use Regex to add a space between the parentheses and the arithmetic operators and digits. 我想使用Regex在括号与算术运算符和数字之间添加一个空格。
For example, I want to replace (+ 2 3)
with ( + 2 3 )
例如,我想将
(+ 2 3)
替换为( + 2 3 )
I wrote this Regex, but doesn't seem to work: 我写了这个正则表达式,但似乎不起作用:
((\(|\))[\d\w +*/-])+
I use Python to replace the characters in the string. 我使用Python替换字符串中的字符。
Regular Expression: ([(]+)|([)]+)
正则表达式:
([(]+)|([)]+)
Substitution: \\1 \\2
替代:
\\1 \\2
Result: ( + 2 3 )
结果:
( + 2 3 )
I think you want something like this, 我想你想要这样的东西
>>> import re
>>> s = "(+ 2 3)"
>>> m = re.sub(r'(?<=\()(?=[-\d+/*])|(?<=[-\d+/*])(?=\))', r' ', s)
>>> m
'( + 2 3 )'
I'm not sure about your requirement, but this is a possible solution: 我不确定您的要求,但这是可能的解决方案:
re.sub(r'([()+*/-]|\w+) *', r'\1 ', s)
Sample input: 输入样例:
(+1 3)
( + 4 (* (/ 6 4)74))
(+ u(- a34 234))
Sample output: 样本输出:
( + 1 3 )
( + 4 ( * ( / 6 4 ) 74 ) )
( + u ( - a34 234 ) )
The slight problem with this solution is that there is an extra space added at the end. 此解决方案的轻微问题是,最后增加了额外的空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.