1

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}" ]

2 Answers 2

2

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 }

Sign up to request clarification or add additional context in comments.

Comments

1

{.*} 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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.