Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

However,

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 at 4:01
    
StringExpression@@... –  rasher May 11 at 4:30
    
@rasher, thank you for the answer. OleksandrR., thank you for your help. –  user1541776 May 11 at 5:01

1 Answer 1

up vote 5 down vote accepted

You're invoking when you should be applying:

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

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

VS

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

Your Answer

 
discard

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.