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]] := 
     chars__~~ WordCharacter.. ~~ num:NumberString :> {chars, num}][[1]];
  • $\begingroup$ Would you describe your use case a bit? My present answer assumes that you want the entire definition to not match if the string pattern does not match. It is appropriate if you are blending string and non-string arguments. However, if you are only operating on strings there may be another syntax that you find more convenient. $\endgroup$
    – Mr.Wizard
    Commented Sep 11, 2013 at 15:08
  • $\begingroup$ @Mr.Wizard The case I'm working with at the moment involves converting a string that contains a specific character sequence into a list of two strings, each of which contains the 2 halves of the string with one being the reverse of the other. In my case, it is simple to solve using a StringSplit and a rule, but I plan on using a fair bit of string manipulation (Splitting things into different chunks and reordering/manipulating them in different ways), and was hoping there was a very simple way to accomplish things like this. $\endgroup$
    – Daniel
    Commented Sep 11, 2013 at 16:19
  • $\begingroup$ If you could give an example of your more complex manipulation, preferably in a new question, I'd be happy to try my hand at making it more convenient. $\endgroup$
    – Mr.Wizard
    Commented Sep 12, 2013 at 1:40

1 Answer 1


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.


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.