Is it possible to use a StringExpression as a pattern for an argument? I.E. something like
foo[chars__~~ WordCharacter.. ~~ num:NumberString] := {chars, num};
At the moment, I'm using a somewhat more convoluted function like
bar[str_String /; StringMatchQ[str, chars__~~ WordCharacter.. ~~ num:NumberString]] :=
StringCases[str,
chars__~~ WordCharacter.. ~~ num:NumberString :> {chars, num}][[1]];
Answer
You cannot use string patterns directly as they are distinct from normal expression patterns, and need to be to prevent ambiguity.
You can however eliminate the double pattern matching by using the shared-body syntax of With and Condition I described in the middle of my answer to Using a PatternTest versus a Condition for pattern matching:
foo[s_String] :=
With[{res = StringCases[s, rule]},
res /; res =!= {}
]
where rule is your pattern and replacement rule. Note that if the pattern is not matched and StringCases returns {} Mathematica will act as if the entire definition did not match, apart from any side-effects induced during the trial evaluation.
Comments
Post a Comment