Take the 2-minute tour ×

I am trying to find a regular expression that matches some custom tags from a text. The tags always have the format [!--sometext--] or [!--sometext:param1--], [!--sometext:param1:param2--]. What I need to do is fetch the "sometext" part and the optional params as "param1:param2" or "param1" and "param2" separately (doesn't matter).

My approach for tags without params is


but how do I match the params part in an elegant way?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Update: OK, third time should be the charm, right? ;-) This works for me in a sample Perl script.

This should do it (and I'm assuming a Perl-compatible reg-ex ... you don't specify what language you're writing this in):


What's going on here?

  1. First we match the [!--
  2. Then we do a match (and capture) on anything that's not a : or a ]
  3. Then we match an optional colon
  4. Then we have an optional, non-greedy match (and capture) of anything that's not either a - or a ] (this should capture all the optional parameters at once)
  5. Then we end it by matching --]

You'll need to split the optional parameters on : to catch the case where there might be more than one.

share|improve this answer
I had something similar to that, but then Blah [!--disclaimer_vat--] blupp [!--disclaimer_vat--] would produce a match for disclaimer_vat--] blupp [!--disclaimer_vat because of greediness. –  smares Aug 29 '12 at 13:17
I think the following works: /\[!--(.+?)(?:\:(.+?))?--\]/ –  smares Aug 29 '12 at 13:22
I changed it to a non-greedy variant. See if that works for you. I guess you could also make sure you don't hit a closing ] in the final captured match: ([^\]-]+?)? –  Jonah Bishop Aug 29 '12 at 13:22

Your Answer


