C# Regex.Split,如何将字符串拆分为括号括起来而不是括号括起来?

问题描述

给定字符串 "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,因为它会为每个括号和非括号组返回匹配项。

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...