I was working on a shortcut that required sorting of a comma separated list of numbers retrieved from the web.
This led me to discover a useful sorting feature in shortcuts and (inspired by episode 34) to use a number of regular expressions.
I thought I’d share the results here as others may find these useful.
The list in question is of the form…
11,2,1,45,7,21
The first shortcut below simply takes this list, splits it up, calls a second shortcut to do the sorting and displays the result.
The trickier piece was doing the actual sorting.
I discovered that the Filter Files action in Shortcuts can be used to sort a list of text strings. Unfortunately if you just apply this to a list of numbers you get something like 1, 11, 2, 21, 45, 7.
To get round this I padded the numbers with leading zeroes to a fixed length (e.g. 011, 002, 001, 045, 007, 021) which generates the correct order when sorted and then removed the leading zeroes again to make the output more readable.
This was achieved using three separate Replace Text actions, each employing regular expressions to do the following…
- Pad the number with an arbitrary number of leading zeroes
- Trim the number to a fixed character length
- Remove the leading zeroes after sorting
This can be seen in the Shortcut below.
Note that I’ve expanded the first Replace Text action to show the Regular Expression switch, which needs to be toggled on for all 3 instances.
Also note that Shortcut currently handles numbers with up to 12 digits. If you wanted to sort longer numbers then you just need to add more zeroes to the text string in the first action.