Suppose I have a string like "a-1_b-2_c-3_d-4"
with numbers, labels, and separators, and I want to get {a-> 1, b-> 2, c-> 3, d-> 4}
, I can do something like:
string1 = "a-1_b-2_c-3_d-4";
vals = ToExpression /@ StringCases[string1,
{"a-" ~~ a : NumberString -> a,
"b-" ~~ b : NumberString -> b,
"c-" ~~ c : NumberString -> c,
"d-" ~~ d : NumberString -> d}];
result = Thread[{a, b, c, d} -> vals]
{a -> 1, b -> 2, c -> 3, d -> 4}
But sometimes my input has one or more parts missing and I would like the default value to be zero in those cases so that "a-1_d-4"
becomes {a -> 1, b -> 0, c -> 0, d -> 4}
. I can't think of a way to do this other than search for each value individually and then check to see if the result was empty. Is there a cleaner way to do it?