-3

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

zkyz
  • 7
  • 3
  • 1
    This lacks context (can `{` `}` constructs be nested? can a quoted part contain escaped `"` symbols? if so, what's the escape syntax? what library or language or tool are you using? specifically, what's the regex flavor/syntax?) and, indeed, a question (do you have an attempt that doesn't quite work? are you stuck somewhere? or do you just expect us to write the code from scratch?). – melpomene Jun 14 '18 at 04:09
  • Now your "result" doesn't even appear in the input string. – melpomene Jun 14 '18 at 04:36
  • sorry. i had a mistake. modfied it. – zkyz Jun 14 '18 at 06:32

1 Answers1

0

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.

Obsidian Age
  • 36,816
  • 9
  • 39
  • 58
  • Doesn't work if one of the outer braces is in quotes. Doesn't work if the string contains newlines. – melpomene Jun 14 '18 at 04:17
  • My first comment refers to your first (and unchanged) regex. Your second regex is just a syntax error. – melpomene Jun 14 '18 at 04:38
  • 1
    This only works in Chrome v62+: https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent/50434875#50434875 – wp78de Jun 14 '18 at 05:29
  • 1
    .. and fails to handle many possible cases: https://regex101.com/r/ogG3zB/1 – wp78de Jun 14 '18 at 06:23