This question already has an answer here:

I have a list of rules and I want to filter it using a pattern for the initial string representing the name of the rule. So that in the example below it filters linearBool even if it is called "linear" or "linearity" or anything starting with "lin"

rules = {runBool -> True, linearBool -> True, ab -> 3}
FilterRules[rules, xx:lin_]


I have tried with MatchQ and Cases but cannot get this simple think to work.



marked as duplicate by Mr.Wizard Feb 25 '15 at 23:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ I have marked this question as a duplicate in an effort to reduce redundant work by the community. If anyone disagrees or has a special method that is applicable only here let me know. $\endgroup$ – Mr.Wizard Feb 25 '15 at 23:13
rules = {runBool -> True, linearBool -> True, ab -> 3, linx -> 10};    
FilterRules[rules, _?(StringMatchQ[ToString[#], "lin*"] &)]
(*{linearBool -> True, linx -> 10}*)
rules = {runBool -> True, linearBool -> True, ab -> 3, linx -> 10};

FilterRules[rules, x_ /; With[{z = ToString@x}, StringLength@z >= 3 && StringTake[z, 3] == "lin"]]

(* {linearBool -> True, linx -> 10} *)

But something like

Pick[rules, StringMatchQ[ToString /@ rules[[All, 1]], "lin*"]]

is cleaner, IMO, and allows flexibility, e.g.

Pick[rules, StringMatchQ[ToString /@ rules[[All, 1]], "lin*" | "a*"]]

(* {linearBool -> True, ab -> 3, linx -> 10} *)

See Albert's comment re: alternative to using ToString.

  • 3
    $\begingroup$ +1, but you probably want to add the information that you can use SymbolName instead of ToString if you want to also match symbols from contexts currently not on $ContextPath, e.g. rules={test`linx->45} (in case one wants that...). $\endgroup$ – Albert Retey Feb 25 '15 at 23:06
  • $\begingroup$ @AlbertRetey: Good point, comment ref'd in answer now. $\endgroup$ – ciao Feb 25 '15 at 23:19

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