3
$\begingroup$

I'm trying to use Switch to process lines from a text file. I know that

StringMatchQ["abc", "a"~~___]

evaluates to True, and

Switch["abc", "a"~~"bc", 1, _, 2]

evaluates to 1

but why does the following evaluate to 2?

Switch["abc", "a"~~___, 1, _, 2]
$\endgroup$

1 Answer 1

6
$\begingroup$

Switch doesn't use the form of the first argument to somehow predict what kind of comparison you want to do. So, it doesn't automatically try a string match just because you passed in the string "abc". And since the expression "a" ~~ ___ is a StringExpression, and "abc" is not a StringExpression, but just a string, then the first match fails.

In the case of

Switch["abc", "a"~~"bc", 1, _, 2]

The expression “a”~~”bc” actually evaluates to just “abc”, so you get an exact match.

You could do this:

Switch["abc", _String?(StringMatchQ["a" ~~ ___]), 1, _, 2]

or just:

Switch["abc", _?(StringMatchQ["a" ~~ ___]), 1, _, 2]

Or you could use Which.

$\endgroup$
1
  • $\begingroup$ Thank you @lericr, great clarity! $\endgroup$
    – Aufheben
    Nov 19, 2023 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.