2=`. !$&@$&" T04`¶d`^^@!T04`¶d`#^@% O`\W?. O`.\w+ \W Explanation
I will use the above input example to walk you through the code:
120 fOo42BaR Stage 1: Substitution
2=`. !$&" The regex itself is just . (matches any non-linefeed character), which is surrounded with !...". However, the 2= is a limit telling Retina to apply the substitution only to the second match of the regex. So we get this:
1!2"0 fOo42BaR Stage 2: Transliteration
T04`¶d`#^@% A transliteration stage simply does a character-by-character substitution. The ¶ represents a linefeed and d expands to 0123456789 (although we can ignore all digits after 2). That means, this transliteration corresponds to the following mapping:
¶012 #^@% The 04 at the front are two limits, which together indicate that only the first four characters from this set should be transliterated. That happens to be the digits on the first line, as well as the linefeed separating the two lines, so we get this:
@!%"^#fOo42BaR At the front of the string we've now got three pairs of these characters:
@! %" ^# Note that the second characters of the pairs are simply in their normal ASCII order (and will always be the same). We'll use these later to sort the groups of characters in the main input into the required order.
The first characters are bit more interesting: their significance is that % comes before digits in the ASCII table, @ comes before upper case letters (but after digits), and ^ comes before lower case letters (but after upper case letters). This will help us group the position markers (i.e. the second character in each pair) with the right set of characters.
Stage 3: Sort
O`\W?. This is a simple sort stage. It matches two characters if the first one isn't a word character (thereby matching all three pairs I just talked about) or a single character otherwise (matching each character of the main input individually), and sorts those strings. This has two purposes: it brings the characters within each group in the correct order (and since sorting is stable, this order won't be messed up in the next stage), and it due to the %@^ markers, it inserts the pairs in the right positions:
%"24@!BOR^#afo Stage 4: Sort
O`.\w+ This stage sorts all matches of the .\w+ regex which, due to greediness, matches one position marker (i.e. one of !"#) together with all the word characters after it. That is, it sorts these three strings, whose order is determined solely by the marker character:
"24 !BOR #afo
While this shuffles around those markers (while leaving the other three markers in place), most importantly it brings the digits and letters in the correct order:
%!BOR@"24^#afo Stage 5: Substitution
\W All that's left is a little clean-up, where we remove all the markers by matching them and replacing them with nothing.