Hi everyone,
How can I create alternatives from a list of strings to be used as a string pattern in StringPosition.
For example, if my function is fed
{"cat","dog","bird}
I want
"cat" | "dog" | "bird"
But if my list has only two strings in it
{"cat","dog"}
I want
"cat" | "dog"
In other words, I want to be able to generate alternatives from a list of unknown length.
I guess a related question is, What is the difference between using
StringPosition[myText,"cat"|"dog"~~WordBoundary]
and
StringPosition[myText,{"cat","dog"}~~WordBoundary]
because both seems to work the same in my tests?
Regards,
Gregory
cfrench
(Christopher French)
January 11, 2016, 11:21pm
2
Alternatives@@{“cat”,“dog”,"bird}
Hi Christopher,
Thanks! Had no idea there was a function called Alternatives because I had only ever seen it as
|
I’m feeling pretty embarrassed.
Gregory
cfrench
(Christopher French)
January 12, 2016, 3:22pm
4
Don’t feel bad. There are plenty of infix symbol shortcuts in common use in Wolfram Language. Many of whom the full function names are not well known or used much at all.
sym:patt is Pattern
patt1_?patt2 is PatternTest
expr1;expr2 is CompoundExpression
Characters that are not letters, letter-like forms, or structural elements are treated by the Wolfram Language as operators. The Wolfram Language has built-in rules for interpreting all operators. The functions to which these operators correspond may...
Thanks once again, Christopher. The language tutorial will be helpful because sometimes I need to use full function names when teaching students Mathematica.
Gregory
Just a remark: One can even be more general (using some operator op)
Infix@*op @@ {"cat", "dog", "bird"}
(* Out: "cat" ~op~ "dog" ~op~ "bird" *)
Henrik
Much obliged, Henrik. I will add this to my growing bag of tips!
Gregory