0
$\begingroup$

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_]

>>linearBool->True

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

Thanks!

$\endgroup$
1
  • $\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
    Commented Feb 25, 2015 at 23:13

2 Answers 2

3
$\begingroup$
rules = {runBool -> True, linearBool -> True, ab -> 3, linx -> 10};    
FilterRules[rules, _?(StringMatchQ[ToString[#], "lin*"] &)]
(*{linearBool -> True, linx -> 10}*)
$\endgroup$
3
$\begingroup$
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.

$\endgroup$
2
  • 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$ Commented Feb 25, 2015 at 23:06
  • $\begingroup$ @AlbertRetey: Good point, comment ref'd in answer now. $\endgroup$
    – ciao
    Commented Feb 25, 2015 at 23:19

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