C# Regex.Split,如何将字符串拆分为被括号包围和不被括号包围?

C# Regex.Split, How do I split string into surrounded by parenthesis and not surrounded by parenthesis?

给定字符串 "I'm not surrounded by parenthesis (but I am) so what.",我如何使用正则表达式将其拆分为如下所示的 string[][0] = "I'm not surrounded by parenthesis " [1] = "(but I am)" [2] = " so what."

或者,有没有办法用相同的字符串替换 (but I am) 但被标签包围?比如说 [b](but I am)[/b].

我试过使用 Regex.Replace 方法和 \(([^\)]+)\) 作为正则表达式。但是我需要方法参数中的替换字符串。鉴于替换字符串应该是与 RegEx 匹配的任何内容,我不太知道如何执行此方法。

对于你的第一个问题,this应该会给你你想要的:

(\([^)]+?\)|[^(]+)

请确保您使用 Regex.Matches,而不是 Regex.Match,因为它将 return 每个括号和非括号组的匹配项。

对于你的第二个问题,像这样的简单调用应该可以做到:

string s = ...;
Regex.Replace(s, @"\([^)]+?\)", @"[b][/b]");