romainberger
romainberger

Reputation: 4558

Regex: capture multiple similar blocks

I'm trying to capture all the {% tag %}...{% endtag %} blocks individually in a string but my regex always returns the whole string from the first opening tag to the last ending tag. How can I make it capture all the blocks separately instead of just one match?

Here is an example of a string:

{% tag %}Lorem ipsum dolor sit amet{% endtag %}

{% tag %}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
{% endtag %}

And my regex (in ruby): /(\{% trans %\}.*\{% endtrans %\})/m

I know the .* is the issue but I haven't found a way to match everything except a closing tag.

Upvotes: 1

Views: 385

Answers (1)

sshashank124
sshashank124

Reputation: 32207

You should use a non-greedy or lazy quantifier (?). This means that .*? will try to match as little as possible instead of the .* matching as much as it can (greedy).

/(\{% trans %\}.*?\{% endtrans %\})/m

DEMO

Upvotes: 3

Related Questions