Barun
Barun

Reputation: 4431

Get string enclosed in curly braces with escaping using RegEx

I want to extract text enclosed inside curly braces. But the complication is that any closing curly brace } with preceding back-slash \ should be included as well in the result.

For example, for the string {abc123*-\\}}, I want to extract the text as abc123*-\\}.

Here is a code sample that I have achieved so far:

var content = '{abc123*-\\}}{sdf}';
var regex = /\{(?<text>([^\}]|(?<=\\)\})*?)\}/;
var firstMatch = content.match(regex); // results 'abc123*-\\'

Upvotes: 0

Views: 261

Answers (2)

Shoyeb Sheikh
Shoyeb Sheikh

Reputation: 2866

Found a solution that works for deep nested curly braces,

Example 1,

var content = '{abc123*-\\}}{sdf}';
var regex = /(?<=\{)(.*?)((?=(?=\}\}))(?=\}).(?!\}{2})|(?!(?=\}\}))(?=\}))/g;
var firstMatch = content.match(regex); 
console.log(firstMatch);

Example 2,

var content = '{{{abc123*-\\}}}}{sdf}}}}}}';
var regex = /(?<=\{)(.*?)((?=(?=\}\}))(?=\}).(?!\}{2})|(?!(?=\}\}))(?=\}))/g;
var firstMatch = content.match(regex); 
console.log(firstMatch);

This will give you all groups of strings in between outer braces { } in a string.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

You may use

var content = '{abc123*-\\}}{sdf}';
var regex = /\{([^\\{}]*(?:\\[^][^\\{}]*)*)}/;
var firstMatch = content.match(regex); // results 'abc123*-\\'
if (firstMatch) {
  console.log(firstMatch[1]);  // => abc123*-\}
}

Details

  • \{ - a { char
  • ([^\\{}]*(?:\\[^][^\\{}]*)*) - Capturing group 1:
    • [^\\{}]* - 0+ chars other than \, { and }
    • (?:\\[^][^\\{}]*)* - 0 or more repetitions of
      • \\[^] - any escaped char (a \ followed with any char)
      • [^\\{}]* - 0+ chars other than \, { and }
  • } - a } char.

See the regex demo and a Regulex graph:

enter image description here

Upvotes: 2

Related Questions