使用正则表达式在大括号之间递归地捕获分组。

huangapple go评论55阅读模式
英文:

Capture groups recursively with regex between braces

问题

如何编写一个正则表达式来捕获这些结构的每个组?

尝试了这个,但只是捕获了全部内容 (.*{.*}$)

想要为每个结构都有一个组,以便可以单独提取每个结构

(NewRequest\s*\{.*?\})|(NewResponse\s*\{.*?\})

完整的结构:

(NewRequest\s*\{.*?\})|(NewResponse\s*\{.*?\})

请注意,这是一个正则表达式,用于匹配文本中的模式。你可以使用编程语言中的正则表达式函数来提取每个匹配的组。

英文:

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

得分: 1

你可以使用以下正则表达式进行匹配:

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

详细解释如下:

  • (?s) - DOTALL 修饰符,表示匹配任意字符,包括换行符。
  • \w+ - 一个或多个单词字符。
  • \s* - 零个或多个空白字符。
  • \{ - 匹配 { 字符。
  • .*? - 匹配任意字符,尽可能少的匹配。
  • } - 匹配 } 字符。

你可以参考正则表达式演示进行测试。

英文:

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.

huangapple
  • 本文由 发表于 2022年7月1日 15:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72825909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定