简体   繁体   English

用正则表达式替换两个不同的字符

[英]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 )

Live Preview here 现场预览

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)

DEMO DEMO

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.

相关问题 Python 正则表达式替换,但前提是正则表达式之前有两个或更多字符 - Python Regex replace but only if two or more characters precede regex expression 正则表达式替换特殊字符在 JS 和 Python 中给出不同的结果 - Regex Replace Special Characters gives different results in JS and Python 正则表达式替换两个不同字符串之前或之后的字符串 - Regex replace string which is before or after two different string 正则表达式替换python中的字符列表 - Regex to replace a list of characters in python Python正则表达式删除和替换字符 - Python regex remove and replace characters 我想以不同的顺序比较两个不同的数据帧,同时忽略特殊字符、空格。 如果相同则更换它 - I want to comapre two different dataframes in different order and also ignoring special characters,spaces. If same then replace it 如何用两个不同的符号替换相同的符号 <remarks> 在两个不同的条件下使用Python中的REGEX - How to replace same symbols with two diferent <remarks> in two different conditions using REGEX in Python 用不同数量的字符替换行 - Replace rows with different number of characters 在python中使用正则表达式替换特殊字符 - Special characters replace using regex in python Python正则表达式:替换匹配中的单个字符 - Python regex: Replace individual characters in a match
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM