英文:
sed - regexp - adding rounded parenthesis on a mathematical expression
问题
我正在尝试编写一个带有正则表达式的sed命令,目的是在要添加的数字周围加上圆括号。
特别是考虑到这个表达式示例 86 * 21 + 7 * 13 * 31 + 26 + 31 * 5
,我想要的结果是 86 * (21 + 7) * 13 * (31 + 26 + 31) * 5
。
我创建了以下sed命令:sed -e 's/\([0-9]\+ +.[0-9]\+\)/(\1)/g' expr.txt
但我只能设置每两个数字之间的圆括号,而不能更多,就像 86 * (21 + 7) * 13 * (31 + 26) + 31 * 5
。
我还尝试使用 sed -e 's/\([0-9]\+ +.*[^\*].*[0-9]\+[^ \*]\)/(\1)/g'
(具体来说,[^\*]
是为了排除乘法)但没有成功。
我该如何达到一个能够在所有连接的加法操作中设置圆括号的结果,例如 86 * (21 + 7) * 13 * (31 + 26 + 31) * 5
?
如何处理特殊情况,例如:
23 + (2 * 53) + (34 * 66) * 55
应该产生((23 + (2 * 53)) + (34 * 66)) * 55
。
英文:
I'm trying to write a sed command with a regex with the purpose to add rounded parenthesis around numbers to be added.
In particular, considering this expression example 86 * 21 + 7 * 13 * 31 + 26 + 31 * 5
I would like to have a result as 86 * (21 + 7) * 13 * (31 + 26 + 31) * 5
.
I created the following sed command: sed -e 's/\([0-9]\+ +.[0-9]\+\)/(\1)/g' expr.txt
but I'm able only to set rounder parenthesis each 2 numbers and not more, like 86 * (21 + 7) * 13 * (31 + 26) + 31 * 5
.
I also tried to use sed -e 's/\([0-9]\+ +.*[^\*].*[0-9]\+[^ \*]\)/(\1)/g'
(specifically `[^*] in order to exclude the multiplication) with no luck.
How can I reach to have a result that is able to set rounded parenthesis for all concatenated addition operations like 86 * (21 + 7) * 13 * (31 + 26 + 31) * 5
?
How to manage particular cases like:
23 + (2 * 53) + (34 * 66) * 55
that should produce((23 + (2 * 53)) + (34 * 66)) * 55
答案1
得分: 4
尝试
sed 's/\([0-9]\+\( + [0-9]\+\)\+\)/()/g';
就我个人而言,我更喜欢 -E
风格,其中 ()
和 +
默认是操作符,必须转义以表示文字:
sed -E 's/([0-9]+( \+ [0-9]+)+)/()/g';
英文:
Try
sed 's/\([0-9]\+\( + [0-9]\+\)\+\)/()/g'
Personally, I prefer the -E
style where ()
and +
are operators by default and have to be escaped to denote literals:
sed -E 's/([0-9]+( \+ [0-9]+)+)/()/g'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论