Ram
Ram

Reputation: 1064

Regex for matching words enclosed in some pattern (that can be dynamically added) and should also return words between enclosed matched words

Let's have the sample string:

"Hello @{MATCH 1} My @[MATCH 2] Wonderful #{MATCH 3} World"

Assuming the following regexes were registered:

[/@\{.+\}/, /@\[.+\]/, /#\{.+\}/]

What I need is for the regex to return the following matches:

["Hello ", "@{MATCH 1}", " My ", "@[MATCH 2]", " Wonderful ", "#{MATCH 3}", " World"]

Currently what I do is compile the registered regexes by joining them with '|' and join a '.+?' pattern at the end. It will turn into something like:

/@\{.+\}|@\[.+\]|#\{.+\}|.+?/g

However this would return these matches:

["H", "e", "l", "l", ..., "@{MATCH 1}", " ", "M", ..., "@[MATCH 2]", ...]

I can live with the current matches, just need to perform extra processing with them. However, I am worried about the performance impact of such number of returned matches. Anyone knows a better regex for returning the matches that I desire? Please do note that the patterns CAN BE DYNAMICALLY REGISTERED. Thanks!

Upvotes: 1

Views: 66

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29419

The following works:

([@#]\{[^}]+\}|@\[[^\]]+\]|[^@#]+)

per this Rubular

Update: Combined the two {} alternatives per @jkshah's helpful comment.

Upvotes: 1

Related Questions