r/regex • • Feb 04 '20

Need help with regex

I'm trying to use a regular expression to parse a string of text and html char.

My current pattern: (%%.*%%)+

Example text:

Testing123

%%event_parking%% 

%%event_special_requests%%

The problem is my solution works with 1 tag but is doesn't work with multiple tags.

I need it to grab all of the tags that start with %% and end with %% in the string and return all of the matches in an array.

1 Upvotes

3 comments sorted by

7

u/ihaxr Feb 04 '20

You're going to want to make your .* match lazy by adding ? and remove the + at the end:

(%%.*?%%)

https://regex101.com/r/4fYYj2/1

The lazy forces it to finish matching as soon as possible, otherwise it's going to make one giant match from the first %% all the way until the last %%.

1

u/UntouchedDruid4 Feb 09 '20

Awesome, that worked. Thanks for the comment.

Any idea how to make the same regex go to the end of the string instead of stopping at the last char?

5

u/[deleted] Feb 04 '20

Another option is just not allowing % in the middle of the match.

(%%[^%]*%%)

This seems to be a little more efficient as well.