0
$\begingroup$

I have let's say a function f[x], but for x I pass a string. And I want to replace that string with a number, if that string matches a pattern. Something like (using wildcard as an example):

f["model2cfs"]/.{"model2*"->9.9}

For the moment I am generating a big list of rules, but this is totally inpractical:

rulist={"model2cfs"->9.9, "model2xy"->9.9, "model2abc"->9.9}

And then I would do:

f[x]/.rulist    

I have tried to find answers here on SE, and from this solution: Replace elements that match pattern, I have adapted it to:

lst={"model2cfs", "model2xy", "model2abc"}
altrule= Alternatives@@lst :> 9.9
f[x]/.altrule

This is more or less fine, but I would have to know in advance the list of possible "models2" , and what I want is to have it very general, so that for each "model2xxx" given, I get the correct replacement.

$\endgroup$
2
  • 3
    $\begingroup$ Use StringMatchQ[] in your replacement rule patterns: f["model2cfs"] /. {str_String /; StringMatchQ[str, "model2*"] -> 9.9} $\endgroup$ Jul 14, 2016 at 18:18
  • 1
    $\begingroup$ I would nest @J.M. 's suggestion in a definition: f[s_String /; StringMatchQ[s, "model2*"]] := f[9.9] $\endgroup$
    – LLlAMnYP
    Jul 15, 2016 at 8:30

0