# FilterRules with pattern for name [duplicate]

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!

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

• 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. – 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.

• +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...). – Albert Retey Feb 25 '15 at 23:06
• @AlbertRetey: Good point, comment ref'd in answer now. – ciao Feb 25 '15 at 23:19