railsuser400
railsuser400

Reputation: 1023

JavaScript Regex for matching multiple instances

Given the following string, what regex matches both substrings within (and including) the curly braces?

var string = "{name: Jackie} works at {company: Google}";

I've tried using string.match(/{.*}/gi) but that returns the entire string as a match:

Array [ "{name: Jackie} works at {company: Google}" ]

Expected output:

Array [ "{name: Jackie}", "{company: Google}" ]

Upvotes: 1

Views: 112

Answers (2)

Tezra
Tezra

Reputation: 8833

{.*} matches a { to the end of the string, and then backs up to the last }. So it just matches from first { to last }. The ? will make the multi match lazy so that it is from first { to next }, BUT it will try to match } at every single step from { to }, and backtracks a bit at each fail, so it also does a lot more work. By matching everything NOT } (like {[^\}]*}), you match the exact same thing, but without all the back tracking. It's always better to match EXACTLY what you want so that you aren't surprised by what it does match. (since .*?} can't match }, don't even let it try)

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

You missed ? in your expression. Problem with your regex({.*}) will match { and then all till last occurrence of }. .* is greedy, where is ? in {.*?} makes it as lazy.

Regex demo

Regex: /{.*?}/g

1. {.*?} this will match { then all till the first occurrence of }

Upvotes: 2

Related Questions