# Parse nested absolute values 2 [duplicate]

Looking at Arnauld's answer, it seems like this version is not really more difficult than the other version, so I made it an optional requirement of the other challenge

The absolute value of a number $$\x\$$ is normally written as $$\|x|\$$. The left and right side of the absolute value uses the same symbol, so it is not immediately obvious how to parse nested absolute values e.g. $$\||1-2|+|3-|4-5|||\$$

Your goal is to parse such an expression containing nested absolute values:

The expression will be given as a string of characters. For simplicity the expression will only contain single digit numbers (or letters if that is easier in your language), the operators + and - (you can use any two distinct characters to represent these operations) and the symbol | for the left and right side of a absolute value. To make the challenger not too easy, it is allowed for numbers to be directly adjacent to absolute values so (2|3| and |2|3 both are valid expressions). See the first version if you do not want to handle that case

Your output should be the same expression in a form that allows to determine how the absolute values are bracketed.

The output has to satisfy the following rules:

• The expression within a absolute value must not end with an operator ( + or - )
• The expression within a absolute value cannot be empty
• Each | has to be part of exactly one absolute value

You may assume there is a valid way to parse the given input. If there is more than one way to parse the expression you can choose any valid solution.

Examples (all possible outputs):

|2|                ->  (2)
|2|+|3|            ->  (2)+(3)
|2|3|-4|           ->  (2)3(-4)
|2|3|-4|           ->  (2(3)-4)
|2|3-|4|           ->  (2)3-(4)
||2||              ->  ((2))
||2|-|3||          ->  ((2)-(3))
|-|-2+3||          ->  (-(-2+3))
|-|-2+3|+|4|-5|    ->  (-(-2+3)+(4)-5)
|-|-2+|-3|+4|-5|   ->  (-(-2+(-3)+4)-5)
||1-2|+|3-|4-5|||  ->  ((1-2)+(3-(4-5)))


This is the shortest solution wins.

• Please let me know if you need me to delete my CW answer in order to delete the post (I don't know if that's required). Commented Dec 5, 2023 at 23:58

# JavaScript (ES6), 52 bytes

I believe my answer to the other version also works for this one... ¯\_(ツ)_/¯

f=s=>s>(s=s.replace(/\|(.*?[\d)])\|/,"(\$1)"))?f(s):s


Try it online!