If I have some strings eg:
str1 = "12-26b-14a";
str2 = "12-21h-14";
and I want to replace the string with a value based on the following rules:
testru = {"12-26b" -> xx, "12-21h" -> yy, "12-42e" -> zz};
I can make the following criteria:
DeleteCases[
ReplaceAll[If[StringMatchQ[str1, # ~~ __], #] & /@
Keys@testru, testru],
Null][[1]]
xx
DeleteCases[
ReplaceAll[If[StringMatchQ[str2, # ~~ __], #] & /@
Keys@testru, testru],
Null][[1]]
yy
This works, but I suspect there are much simpler/ more elegant ways to perform such a seemingly simple task.
In particular, ReplaceAll
feels like overkill for a single element!
Any suggestions for an improved method?
EDIT
I'd rather not mess with the structure of testru
since I use this list for other purposes.
Also the strings do not have definite lengths so clipping the string by a certain number of characters is not viable.
StringStartsQ[]
for matching suffices. $\endgroup$str1
andstr2
to transform? $\endgroup$