Nick M
Nick M

Reputation: 2522

Somewhat complex ruby regular expression

I have a bunch of strings I translate within views of a CMS as follows:

<a href="blah">[translate[This is the best website in the whole wide world!]]</a>

This works great thanks to this solution however I would like to take it to the next step and use tags such as [website_name] inside the [translate[........]] tags. Doing so with the current regexp skips the fragment.

This is what I am using now:

(/\[translate\[([^\]]*)\]\]/)

Is it possible to make this ignore any [tags] inside? Basically I am trying to make it stop at ]] instead of anything else.

so basically for [translate[This is the best [product] in the whole wide world!]] the output would be This is the best [product] in the whole wide world!

TIA

Upvotes: 0

Views: 81

Answers (1)

hwnd
hwnd

Reputation: 70722

You need to use a recursive regular expression here.

\[translate\[((?:[^\[\]]++|\[\g<1>\])++)\]\]

Rubular (Ruby 1.9.2)+

If you are using (Ruby 1.8.7), as stated in the comments:

\[translate\[((?>[^\[\]]+|\[\g<1>\])*)\]\]

Upvotes: 2

Related Questions