1
$\begingroup$

Considering we have an association like:

asc1 =  <|"a.s.r"->1, "a.s.r345" -> 45, "asc" -> "cas", "qwrs" -> 78, "a.s.r[4]/vu" -> 4, "es" -> 74|>

How to extract an asc2 to include only the pairs where key starts with "a.s.r", as the following:

asc2 = <|"a.s.r"->1, "a.s.r345" -> 45, "a.s.r[4]/vu" -> 4|>

Thank you!

$\endgroup$

1 Answer 1

6
$\begingroup$

Cleanest may be KeySelect and StringMatchQ:

asc1 // KeySelect[StringMatchQ[#, "a.s.r*"] &]
<|"a.s.r" -> 1, "a.s.r345" -> 45, "a.s.r[4]/vu" -> 4|>

Responding to the follow-up questions in the comments:

Count[Keys @ asc1, s_String /; StringMatchQ[s, "a.s.r*"]]

3

asc1 // KeySelect[! StringMatchQ[#, "a.s.r*"] &]
<|"asc" -> "cas", "qwrs" -> 78, "es" -> 74|>

Also:

GroupBy[Normal@asc1, StringMatchQ[First@#, "a.s.r*"] &, Association]
<|True -> <|"a.s.r" -> 1, "a.s.r345" -> 45, "a.s.r[4]/vu" -> 4|>, 
 False -> <|"asc" -> "cas", "qwrs" -> 78, "es" -> 74|>|>

Or to modify asc1 in-place:

asc1 ~KeyDropFrom~ Keys[asc2];

asc1
<|"asc" -> "cas", "qwrs" -> 78, "es" -> 74|>
$\endgroup$
3
  • $\begingroup$ Thank you! Is there a way to check if I have more than 1 "a.s.r*" or any other key in my association? $\endgroup$
    – SuTron
    Jul 23, 2015 at 20:49
  • $\begingroup$ And also how can I extract asc1 from asc, so that to have asc2 without asc1 $\endgroup$
    – SuTron
    Jul 23, 2015 at 20:55
  • 1
    $\begingroup$ @SuTron See update. $\endgroup$
    – Mr.Wizard
    Jul 23, 2015 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.