o1n3n21
o1n3n21

Reputation: 364

Regex: Only match non-nested groups

I have some text, in a similar pattern to:

new{test}anotherone{test{nest}}new1{test1}new2{test2}

I'm new to Regex, and trying to create a pattern which matches groups such that for each match: Group 1: new Group 2: test

I have this working with ([\S][a-z#-()->]+)\{([^?+]*?)\} using JavaScript

However, I want to ignore the block with the nesting, such that the anotherone{test{nest}} is ignored from the matching. Here's my attempt on Regex101

Thanks in advance!

Update: The string might also have nested inside the nested part, e.g.

new{test}ignore_this{test1{test1}{test2{test2}}new{test}new{test}

Such that it should only match: Group1: new / Group2: test

Upvotes: 3

Views: 237

Answers (1)

anubhava
anubhava

Reputation: 785721

You may try this regex to match each pair of new and test (3 pairs in your input):

(?<!{)\b([^{}]+){([^{}]*)}(?![^{}]*})

Updated RegEx Demo

RegEx Details:

  • (?<!{): Make sure we don't have { at previous position
  • \b: Word boundary
  • ([^{}]+): Match 1+ of any character that is not { and } in group #1
  • {: Match a {
  • ([^{}]*): Match 0+ of any character that is not { and } in group #2
  • }: Match a }
  • (?![^{}]*}): Negative lookahead to assert that we don't have a closing } ahead without any { and } in between

Upvotes: 2

Related Questions