Search code examples
javascriptregexregex-greedy

regexp ignore some context after matching


i want to solve regular expression in javascript for:

ignore } character wrapped context by quote. but must match } character out of quote.

example: "The sentense { he said 'hello, {somebody}', she said 'hi, {somebody}' } got a something."

result: { he said 'hello, {somebody}', she said 'hi, {somebody}' }

thanks for your help


Solution

  • The context is a little vague, but assuming you want the result to contain everything inside of (and including) the outer curly braces, you can just use /{.*}/g.

    This can be seen in the following:

    var regex = /{.*}/g;
    var string = 'The sentense { he said "hello, {somebody}" } got a something.';
    
    console.log(string.match(regex)[0]);

    Or if you want to grab all three components, you can use the slightly-more-complicated regex
    /({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g:

    Breaking this down:

    1. ({.*(?={)) - Group anything up to the second {
    2. (.*(?<=.*})) - Grab everything inside the inner curly braces and group it
    3. (?:.*) - Group anything up to the next }
    4. } - Continue searching for the next } (but don't group it)
    5. (.*) - Group anything after that

    This can be seen in JavaScript here:

    var regex = /({.*(?={))(.*(?<=.*}))(?:.*)}(.*)/g;
    var string = 'The sentense { he said "hello, {somebody}" } got a something.';
    
    string.replace(regex, function(match, g1, g2, g3) {
      console.log(match);
      console.log(g1);
      console.log(g2);
      console.log(g3);
    });

    And can be seen working on Regex101 here.