3
$\begingroup$

I have an Association asc that has mixed type Keys:

asc = <|"b1" -> 2, "a1" -> 1, c3 -> 3|>;

I try to select based on excluding a string pattern via Not @ StringMatchQ but without succes:

KeySelect[asc, ! StringMatchQ["b" ~~ __?DigitQ]]

(* <||> *)

The selection based on StringMatchQ by itself does work, but I get the warning that a String was expected as Key for the third association:

KeySelect[asc, StringMatchQ["b" ~~ __?DigitQ]]

(* 
StringMatchQ: String or list of strings expected ....
<|"b1" -> 2|> 
*)

I would like to understand:

  1. how do I avoid this error message
  2. what is wrong with the attempt using Not @ StringMatchQ?
$\endgroup$
  • 1
    $\begingroup$ Take a look at: (! StringMatchQ["any"])@"any" // FullForm $\endgroup$ – Kuba Nov 28 '18 at 7:13
  • $\begingroup$ @Kuba, it took me a while to understand this and why the original construct would not work, but this improved my understanding. Thanks! $\endgroup$ – Sander Nov 28 '18 at 23:31
3
$\begingroup$
KeySelect[Or[Not@StringQ@#, Not@StringMatchQ["b" ~~ DigitCharacter ..]@#] &][asc]

<|"a1" -> 1, c3 -> 3|>

Alternatively:

KeySelect[Nand[StringQ@#, StringMatchQ["b" ~~ __?DigitQ]@#] &]@asc

<|"a1" -> 1, c3 -> 3|>

KeySelect[MatchQ[Except[_String] |
    _String?(Not@*StringMatchQ["b" ~~ DigitCharacter ..])]]@asc

<|"a1" -> 1, c3 -> 3|>

KeySelect[MatchQ[_String?(Not@*StringMatchQ["b" ~~ DigitCharacter ..])]]@asc

<|"a1" -> 1|>

$\endgroup$
  • $\begingroup$ Thanks for your help. $\endgroup$ – Sander Nov 28 '18 at 23:31
  • $\begingroup$ @Sander, my pleasure. Thank you for the accept. $\endgroup$ – kglr Nov 28 '18 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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