Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I try to construct patterns using Riffle and Except

StringExpression@Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..]

and expect it to match "a_b_c", but not "a_bc" because Except is repeated .. one or more times.


StringMatchQ["a_bc", StringExpression@Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..]]

returns True. Could anyone explain why is it so?

share|improve this question
Well, I don't know, but I think this has something to do with how the pattern is translated into a Perl-compatible regular expression and then understood by the PCRE library. The regex is given by First@StringPattern`PatternConvert@Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..] and comes out as (?ms)(?:a|(?:[^=,])+|b|(?:[^=,])+|c). Perhaps someone with more experience of using regular expressions will be able to suggest why this behaves as it does. – Oleksandr R. May 11 '14 at 4:01
StringExpression@@... – ciao May 11 '14 at 4:30
@rasher, thank you for the answer. OleksandrR., thank you for your help. – user1541776 May 11 '14 at 5:01
up vote 7 down vote accepted

You're invoking when you should be applying:

StringExpression@Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..]

(* StringExpression[{"a", Except[{"=", ","}] .., "b",  Except[{"=", ","}] .., "c"}] *)


StringExpression @@ Riffle[{"a", "b", "c"}, Except[{"=", ","}] ..]

(* "a" ~~ Except[{"=", ","}] .. ~~ "b" ~~ Except[{"=", ","}] .. ~~ "c" *)

Note that the first way ends up equivalent to

StringMatchQ[...,{"a", Except[{"=", ","}] .., "b", Except[{"=", ","}] .., "c"}]

which of course gives you unwanted matches (recall that the list is treated as alternatives).

Using application, the correct

StringMatchQ[...,"a" ~~ Except[{"=", ","}] .. ~~ "b" ~~ Except[{"=", ","}] .. ~~ "c"]

is generated, giving the desired results.

share|improve this answer
(+1) Didn't know that StringMatchQ accepts list as a second argument. Is it documented anywhere? – Alexey Popkov May 22 at 20:21
@AlexeyPopkov: It must be... but I'll be damned if I can find it. I've been using that form for ages... StringCases has that form documented, perhaps one of those "...I wonder if this works here...", it did, and I've used it since. – ciao May 22 at 20:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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