符合括号内的所有内容的正则忽略嵌套

发布于 2025-01-19 08:37:00 字数 469 浏览 1 评论 0原文

我正在寻找一个正则表达式规则来匹配方括号内的所有内容,包括括号并忽略内部可能的括号。例如:

[value] in the [text[42]] and [1[2[3]]]!

我需要提取 [value][text[42]][1[2[3]]]

我使用

\[(.*?)\]

这里有更多示例 - https://regex101.com/r/Xp4ghi/1

PS我将在.NET中使用它

I am looking for a regex rule to match everything inside square brackets, including the brackets and ignoring the possible brackets inside. E.g. from:

[value] in the [text[42]] and [1[2[3]]]!

I need to extract [value], [text[42]] and [1[2[3]]].

I use

\[(.*?)\]

Here are more expamples - https://regex101.com/r/Xp4ghi/1

P.S. I am going to use it in .NET

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兰花执着 2025-01-26 08:37:00

您可以使用

\[(?>[^][]+|(?<c>)\[|(?<-c>)])+]

regex demo 详细信息

  • \ [ - a [ char
  • (?&gt; [^] [] []+|(? \ [|(?&lt; -c&gt;)])+ - 一次或多个出现
    • [^] []+| - 一个或多个字符以外的][,或,或
    • (?
    • (?


  • ] - a ] char。

You can use

\[(?>[^][]+|(?<c>)\[|(?<-c>)])+]

See the regex demo. Details:

  • \[ - a [ char
  • (?>[^][]+|(?<c>)\[|(?<-c>)])+ - one or more occurrences of
    • [^][]+| - one or more chars other than ] and [, or
    • (?<c>)\[| - a [ char and a value is pushed onto Group "c" stack, or
    • (?<-c>)] - a ] char and a value is popped off the Group "c" stack
  • ] - a ] char.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文