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
  • 1
    $\begingroup$ For that specific example StringMatchQ["a*" | "b*"]["abcd"] $\endgroup$ Commented Jan 27, 2020 at 22:41

1 Answer 1

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

$\endgroup$

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.