# Create pattern condition dynamically

Suppose i have a function

condition[pattern_,list_]:=With[
{x=Unique["x"]},
Condition[Pattern[Evaluate[x],pattern],Not@StringContainsQ[x,list]]
];


If i evaluate condition[_,{"a","b","c"}] i get an error.

But if i manually evaluate the right hand side i get the required result.

With[
{x=Unique["x"]},
Condition[Pattern[Evaluate[x],_],Not@StringContainsQ[x,{"a","b","c"}]]
]


result is

x56_ /; ! StringContainsQ[x56, {"a", "b", "c"}]

• You could "isolate" Condition head by wrapping it with Identity: condition[pattern_, list_] := With[{x = Unique@"x"}, Identity[Condition][x : pattern, Not@StringContainsQ[x, list]]]. – jkuczm Aug 10 '18 at 9:32
• In case of simple condition that just applies function to whole expression matched by pattern you could use PatternTest instead of Condition: condition[pattern_, list_] := pattern?(Not@*StringContainsQ[list]). – jkuczm Aug 10 '18 at 9:33

From the help for With:

You can use With[{vars},body/;cond] as the right-hand side of a transformation rule with a condition attached.

Basically, your code is that construction. Avoid having condition as the first head of the body of With:

condition[pattern_, list_] :=
With[{x = Unique["x"]},
Apply[Condition, {Pattern[x, pattern],
Not@StringContainsQ[x, list]}]];

condition[_, {"a", "b", "c"}]
(*x11_ /; ! StringContainsQ[x11, {"a", "b", "c"}]*)

• You might want to prevent evaluation of Condition arguments by using holding wrapper instead of list: Condition @@ Hold[x : pattern, Not@StringContainsQ[x, list]] – jkuczm Aug 10 '18 at 9:28