Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Repeat pattern n times, with variation on final repetition

I have a regular expression which is intended to match a specific syntax, n times, with a pipe (|) following each occurrence, except for the final occurrence. Currently, my pattern is along the lines of (pattern)\|{3}, but this doesn't satisfy the requirement that there is no trailing pipe. Is there anyway I can accomplish this without repeating (pattern)? The best solution I can think of is (pattern)\|{2}(pattern).

Valid Example:

*|401|[2-10]

Invalid Example:

*|401|[2-10]|

The value of (pattern) is extraneous to answering my specific question, but for completeness, here it is in its current form: (?:(?:((\*)|(\[[\w+ ]\-[\w+ ]\])|(\d+)))\|){3}

Edit

This is being consumed within .NET and JavaScript.

like image 274
Nathan Taylor Avatar asked Dec 19 '14 00:12

Nathan Taylor


1 Answers

There is a simple solution, if you're matching the entire input string:

(?:pattern(?:\|(?!$)|$)){3}

Which means: match your pattern followed by:

  • either \|(?!$): a pipe not followed by the end of the string
  • or $ the end of the string

3 times.


For your specific pattern, this would be:

^(?:(?:((\*)|(\[[\w+ ]\-[\w+ ]\])|(\d+)))(?:\|(?!$)|$)){3}

I also prefixed the pattern with ^, since this solution works only if you match the entire input anyway.

like image 119
Lucas Trzesniewski Avatar answered Oct 08 '22 14:10

Lucas Trzesniewski