Alternatives seems to work fine with these simple patterns
StringMatchQ["Eric", Alternatives["Eric", "Geoff"]]
(* True *)
StringMatchQ["Eric", Alternatives["Geoff", "Eric"]]
(* True *)
I have a more complex pattern that matches strings enclosed with parenthesis and optionally the string "sh" at the end. The patterns are below where I assign them to a variable
patternText =
StartOfString ~~ "(" ~~
textContent : ((Join[{WordCharacter}, {"-", "+", "\\", ".", ",",
"/", ":", " "}] ..)) ~~ ")" ~~ EndOfString
patternTextShow =
StartOfString ~~ "(" ~~
textContent : (Join[{WordCharacter}, {"-", "+", "\\", ".", ",", "/",
":", " "}] ..) ~~ ")sh" ~~ EndOfString
The patterns work fine by themselves
StringMatchQ["(Eric)", patternText]
(* True *)
StringMatchQ["(Eric)", patternTextShow]
(* False *)
StringMatchQ["(Eric)sh", patternText]
(* False *)
StringMatchQ["(Eric)sh", patternTextShow]
(* True *)
The results are as expected.
When I use Alternatives
, however, it only works if the matching pattern is first, fails otherwise.
StringMatchQ["(Eric)", Alternatives[patternTextShow, patternText]]
(* False *)
StringMatchQ["(Eric)", Alternatives[patternText, patternTextShow]]
(* True *)
StringMatchQ["(Eric)sh", Alternatives[patternTextShow, patternText]]
(* True *)
StringMatchQ["(Eric)sh", Alternatives[patternText, patternTextShow]]
(* False *)
Why is this?
I found that using Or
solved the problem but would like to understand why the Alternatives
approach fails.
Or[
StringMatchQ["(Eric)", patternTextShow],
StringMatchQ["(Eric)", patternText]
]
(* True *)
Or[
StringMatchQ["(Eric)", patternText],
StringMatchQ["(Eric)", patternTextShow]
]
(* True *)
Or[
StringMatchQ["(Eric)sh", patternTextShow],
StringMatchQ["(Eric)sh", patternText]
]
(* True *)
Or[
StringMatchQ["(Eric)sh", patternText],
StringMatchQ["(Eric)sh", patternTextShow]
]
(* True *)