在C#中拆分字符串以提取括号中的值并保留它们
我需要拆分一个字符串,以使用正则表达式提取字符串数组中的括号和数据,并保留括号 摘自在C#中拆分字符串以提取括号中的值并保留它们,c#,.net,C#,.net,我需要拆分一个字符串,以使用正则表达式提取字符串数组中的括号和数据,并保留括号 摘自 1-2-3(0)(1) 到 我构造了这个正则表达式,但无法使其工作 String phrase= "123(0)(1)" String[] results = Regex.Split(phrase,"\\r+(?:\\(.*\\))"); 若括号中的两个始终在一起,您可以尝试使用substring方法 phrase = phrase.Substring(phrase.FirstIndexOf("("));
1-2-3(0)(1)
到
我构造了这个正则表达式,但无法使其工作
String phrase= "123(0)(1)"
String[] results = Regex.Split(phrase,"\\r+(?:\\(.*\\))");
若括号中的两个始终在一起,您可以尝试使用substring方法
phrase = phrase.Substring(phrase.FirstIndexOf("("));
可能必须在后面加-1。您可以使用
(\(\d\)
模式提取括号中的数字
例如
您可以改用Regex.Matches方法
string phrase = "123(0)(1)";
string[] results = Regex.Matches(phrase, @"\(.*?\)").Cast<Match>().Select(m => m.Value).ToArray();
stringphrase=“123(0)(1)”;
string[]results=Regex.Matches(短语@“\(.*?\)”).Cast().Select(m=>m.Value.ToArray();
\r
与回车符匹配。应该是\d
Regex.Matches(input,@“\([^\)]+\”)
?可能是重复的,只需用方括号代替括号。Regex.Matches(input,@“\(.*)”)
这就是我想要的。它工作得很好。Tnx,这也行。Tnx。
var input = "1-2-3(0)(1)";
Regex pattern = new Regex(@"(\(\d\))");
var matches = pattern.Matches(input);
foreach (Match match in matches)
{
foreach (Capture capture in match.Captures)
{
Console.WriteLine(capture.Value);
}
}
string phrase = "123(0)(1)";
string[] results = Regex.Matches(phrase, @"\(.*?\)").Cast<Match>().Select(m => m.Value).ToArray();