If you have a string
string="<ALK>ene"
and I have a list
alk={"meth", "eth", "prop", "but", "pent"}
, what function could I use to automatically create a list
{"methene","ethene","propene","butene","pentene"}
, i.e. with "<ALK>"
replaced by each element of alk
in turn? I could do something like alkenenames[ALK_] := StringJoin[ALK, "ene"];Map[alkenenames, alknames];
- but instead of defining functions I would like to be able to define string with pattern replacement rules embedded in them as above. How do I do this in Mathematica?
Edit: actually one more question - I noticed that the different proposed solutions below behave differently if the string happens not to contain "<ALK>"
- in one solution returning an empty list, and in another one returning a list of your original string duplicated n times, where n is the length of the list alk. In actual fact I would like the function to just return the original string if <ALK>
does not occur in it. Also, I was wondering what would be the most elegant solution to also allow multiple occurences of <ALK>
in the string, which would then be replaced in a combinatorial fashion.
(i.e. replacing the first occurrence of <ALK>
by each alk element in turn, and then replacing the second occurrence of <ALK>
by each alk element in turn as well, and so on)
Block[{string = "<ALK>yl <ALK>one <ALK>elone", pos}, pos = StringPosition[string, "<ALK>"]; StringReplacePart[string, {##}, pos] & @@@ Tuples[alk, Length@pos]]
(Ifstring
doesn't contain "<ALK>" at all, then it just returns it without change.) $\endgroup$