Ternary-if Converter

Python 2, 126 121 120 114 100 bytes

lambda s:findall(' (.=)',s)[0]+sub('if.(.*?)\)(.=)?',r'\1?',sub('.{5} (.=)?',':',s))
from re import*

Try it online!


Saved:

  • -1 byte, thanks to Kevin Cruijssen

Perl 5 -p, 50 49 48 bytes

s/if.(.*?)\)(.=)/\2\1?/g;s/.if./?/g;s/;.{6}=/:/g

Try it online!

The 48 byte version is inspired by Neil's Retina answer.

Explanation

# Replace "if(e1)if(e2)x=" with "x=e1)if(e2?"
s/if.(.*?)\)(.=)/\2\1?/g;
# Replace ")if(" with "?"
s/.if./?/g;
# Replace ";else x=" with ":"
s/;.{6}=/:/g

Old 49 byte solution

s/.{5} (.=)?/:/g;s/if.(.*?)\)(.=)?/\1?/g;$_=$2.$_

Retina 0.8.2, 32 bytes

+r`if.(.*?)\)(.=)
$2$1?
;.{6}=
:

Try it online! Explanation:

r`if.(.*?)\)(.=)
$2$1?

Handle an if immediately before an assignment by moving the assignment before the condition and appending a ?. The stage is matched right-to-left to ensure we get the if closest to the assignment, while the \) ensures that we don't match else by mistake.

+

Repeat the stage to take care of nested ifs.

;.{6}=
:

Any remaining assignments are elses so replace the ;else ?= with a :.