Message Boards Message Boards

0
|
4367 Views
|
6 Replies
|
5 Total Likes
View groups...
Share
Share this post:

How can I generate alternatives from a list of strings?

Posted 9 years ago

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

POSTED BY: Gregory Lypny
6 Replies

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

POSTED BY: Henrik Schachner
Posted 9 years ago

Much obliged, Henrik. I will add this to my growing bag of tips!

Gregory

POSTED BY: Gregory Lypny

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

https://reference.wolfram.com/language/tutorial/OperatorInputForms.html

Posted 9 years ago

Thanks once again, Christopher. The language tutorial will be helpful because sometimes I need to use full function names when teaching students Mathematica.

Gregory

POSTED BY: Gregory Lypny
Posted 9 years ago

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

POSTED BY: Gregory Lypny
Alternatives@@{"cat","dog","bird}
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract