Quantcast
Channel: Active questions tagged string-manipulation - Mathematica Stack Exchange
Viewing all articles
Browse latest Browse all 188

How to return a default value if no match is found in search of string

$
0
0

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?


Viewing all articles
Browse latest Browse all 188

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>