简体   繁体   中英

Regular expression between curly braces, but ignore nested

I'm looking for a regular expression that find strings between curly braces, but ignores nested (if there are). For example, the next string:

reset survey 888 ${d14322a2-bc13-4fcb-9da3-{sdfdsf}e2346a7d58ec} for the participant ${c45e9bc0-6043-4aa1-8de0-27f8f8aade82}

Should only match the next two:

  1. d14322a2-bc13-4fcb-9da3-{sdfdsf}e2346a7d58ec
  2. c45e9bc0-6043-4aa1-8de0-27f8f8aade82

Based on the answers, I'm going to add another example:

{@aaa Location}
{@eee header}
{@bbb { http://www.uytuty.org/879/fghdhgfd }hgjdg}
{@gfh fdgdf gd dfgfdg.}

It should match:

  1. @aaa Location
  2. @eee header
  3. @bbb { http://www.uytuty.org/879/fghdhgfd }hgjdg
  4. @gfh fdgdf gd dfgfdg.

This is a job for recursion.

If your regex flavour supports it, you can use:

(?<={)([^{}]++|\{(?1)\})+(?=})

Demo & explanation

(?!\\{)[\\w\\-\\{\\}]+(?=\\})

Let's break it down:

  • (?!abc) - negative look ahead. The matching string is excluded from the result.
  • (?=abc) - positive look ahead. The matching string is excluded from the result.
  • [\\w\\-\\{\\}]+ - any alphanumeric character (including underscore) and curly braces.

Tested on https://regexr.com/4q128

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM