Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
o1n3n21 Avatar asked Jul 19 '26 06:07

o1n3n21


1 Answers

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
like image 131
anubhava Avatar answered Jul 20 '26 19:07

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!