Take the 2-minute tour ×

I've a sequence of comma separated words like x1,x2,x3.... Some words in this sequence maybe optional i.e the sequence x1,x3,x4,x6 is valid with x2 and x5 being optional, and the rest of the words being mandatory. The above sequence can be repeated for maximum of n number of times.

For ex, the sequence of words x1,x2,x3 can be repeated maximum of 3 times with x2 being optional, the following is a valid sequence: x1,x3,x1,x2,x3,x1,x3

How do I validate the above using a regex pattern?

I tried something like (,{0,1}x1,(x2,){0,1}x3,{0,1}){3} But the above will work for all multiples of three, if I use {1,3} then any amount of repetitions will match because they're multiples of 1 {1,3}.

share|improve this question
Could you provide some more example sequences, both valid and invalid? Example: Are you strict on the numbers going in increased order? –  ohaal May 16 '12 at 9:46

1 Answer 1

Your example works fine except that, as you note, you are checking only whether the target string contains a matching character sequence. You need to anchor the regex at the start and end of the string using \A and \z to make sure the entire string matches.

Also, {0,1} is more simply written as ?, and capturing parentheses ( ... ) are better written as non-capturing ones (?: ... ) when you don't need to capture the substrings.

Try this modification of your regular expression, which uses the /x modifier to allow insignificant whitespace to be added to the expression to lay it out better.

m/ \A (?: x1, (?: x2, )? x3 ,? ){1,3} \z /x;
share|improve this answer
Good answer, but the regex will yield some false positives: for example, x1,x2,x3x1,x2,x3 (note the missing comma joining to two sub-sequences). Rather than making the final comma optional, you could use alternation to specify either a comma or end-of-string: (?: , | \z). –  FMc May 19 '12 at 15:44

Your Answer


