# How to correctly sort string list based on numeric substring pattern?

I'm having a hard time sorting a big list of filenames. I've tried a bunch of things, and tried to adapt this answer but seemed over-killing(?)...

(*My list of filenames*)
dummyList = {"gibberish_A1p1_B0p1.mx", "gibberish_A11p11_B0p.mx","gibberish_A0p1_B0p2.mx"};


Suppose I have a string list like the one below. It is a list of filenames. Each name indicates the values of two parameters, A and B, in this format: if A was 0.0, then the name contains the substring 0p (the p just means 'period'), if it was 1.1, then the substring would be 1p1 and so forth (so you can guess the same goes for B).

Anyways, suppose I want to order the list, so that the files are ordered by the value of either A or B.

So, let's say I want to order them by A, then I'd like to get:

(*Correct sorting*)
{"gibberish_A0p1_B0p2.mx", "gibberish_A1p1_B0p1.mx", "gibberish_A11p11_B0p.mx"}


But instead I kept getting something like this:

AlphabeticSort[dummyList]
{"gibberish_A0p1_B0p2.mx", "gibberish_A11p11_B0p.mx", "gibberish_A1p1_B0p1.mx"}


Now, these are simple cases. In my actual application, I'd like to do the proper sorting for either A, B, or something else (say C), and the gibberish is some other complicated substring.

Thanks!

One solution is to use SortBy.

We need a function that extracts the numeric values in your string. Here is one solution:

pvalue[xpy_]:=ToExpression[StringReplace[xpy,"p"->"."]];
abcvalue[ABC_][filename_]:=pvalue[First[StringSplit[Last[StringSplit[filename,"_"<>ABC]],"_"|"."]]];


To see how they work, try

pvalue["54p432"]
(* 54.432 *)

abcvalue["A"]["gibberish_A0p1_B0p2.mx"]
(* 0.1 *)

abcvalue["B"]["gibberish_A0p1_B0p2.mx"]
(* 0.2 *)


Warning. The function abcvalue assumes that gibberish does not contain _A as a substring and so on. If it does, then one will have to make abcvalue slightly more selective.

In any case, now you'd simply do this:

SortBy[dummyList,abcvalue["A"]]
SortBy[dummyList,abcvalue["B"]]

• Cool, this really helped me getting started, just had to adjust for the shenanigans in gibberish. Jul 16, 2022 at 5:57