user519477
user519477

Reputation:

Regular expression for finding custom tags

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?

Upvotes: 1

Views: 225

Answers (1)

Jonah Bishop
Jonah Bishop

Reputation: 12571

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.

Upvotes: 1

Related Questions