2
$\begingroup$

Why when trying to find whether one (out of several) patterns matches an expression - using StringMatchQ - all of them seem to be ignored and no matches are found? In this simple example I try to find out whether or not the 4-letter-long string "abcd" starts with an "a"

StringMatchQ[
  StartOfString ~~ "a" ~~ _ ~~ _ ~~ _]["abcd"]

True

However, when I try to test whether it starts with either an "a" or, say, a "b",

StringMatchQ[
      StartOfString ~~ "a" ~~ _ ~~ _ ~~ _|StartOfString ~~ "b" ~~ _ ~~ _ ~~ _]["abcd"]

False

Shouldn't it be true since the first of the two patterns is a match? Isn't this used to specify that either one pattern or the other is the pattern to be matched?

$\endgroup$
  • 1
    $\begingroup$ For that specific example StringMatchQ["a*" | "b*"]["abcd"] $\endgroup$ – Rohit Namjoshi Jan 27 at 22:41
3
$\begingroup$

Wrap the patterns with parantheses:

StringMatchQ[(StartOfString ~~ "a" ~~ _ ~~ _ ~~ _) | 
  (StartOfString ~~ "b" ~~ _ ~~ _ ~~ _)]["abcd"]

True

Alternatively, use the input form of Alternatives:

StringMatchQ[Alternatives[StartOfString ~~ "a" ~~ _ ~~ _ ~~ _, 
   StartOfString ~~ "b" ~~ _ ~~ _ ~~ _]]["abcd"]

True

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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