Capture groups recursively with regex between braces

Viewed 33

How to write a regex, that capture every group of these structures?

Tried this, but this just captures everything (.*{.*}$)

Want to have a group for each so that I can extract each one individually

NewRequest {
    string id = 1;
    string name = 2;
}
NewResponse {
    int64 id = 1;
    string name = 2;
}

Complete structure:

NewRequest {
    string id = 1;
    string name = 2;
}

 NewResponse {
    int64 id = 1;
    string name = 2;
}
 NewResponse {
    int64 id = 1;
    string name = 2;
}
 NewResponse {
    int64 id = 1;
    string name = 2;
}
 NewResponse {
    int64 id = 1;
    string name = 2;
}
1 Answers

You can use

(?s)\w+\s*\{.*?}
\w+\s*\{[^{}]*}

See the regex demo.

Details:

  • (?s) - a DOTALL modifier
  • \w+ - one or more word chars
  • \s* - zero or more whitespaces
  • \{ - a { char
  • .*? - any zero or more chars as few as possible
  • } - a } char.
Related