You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#提取指定括号内子串问题:如何获取目标括号中的内容

解决括号内容提取的问题

我明白你现在遇到的困扰啦——用LastIndexOf(")")作为结束索引时,会误取到整个字符串最后一个右括号的位置,导致截取的内容包含了后面不需要的部分,就像你例子里会把, Reproductive Disease(Maternal)也带进来,对吧?

问题根源

LastIndexOf(")")会返回整个字符串中最后一个右括号的位置,而你实际需要的是目标短语(比如High Blood Pressure()之后的第一个右括号,这俩位置差了好多呢!

修正后的基础代码

首先先修正你代码里的拼写小错误(High Blood Pressue少了个字母r,应该是High Blood Pressure),然后把结束索引的计算改成IndexOf(")", From),这样就能精准定位到目标左括号之后的第一个右括号:

String fammedhistory= "High Blood Pressure(Paternal), Reproductive Disease(Maternal)";
// 修正拼写错误,找到目标左括号的起始位置
int From = fammedhistory.IndexOf("High Blood Pressure(") + "High Blood Pressure(".Length;
// 找From位置之后的第一个右括号,而不是最后一个
int To = fammedhistory.IndexOf(")", From);
String result = fammedhistory.Substring(From, To - From);
// 现在result的值就是"Paternal",符合预期啦

更健壮的进阶方案:正则表达式

如果你的场景里需要提取多个类似括号里的内容(比如同时拿到Paternal和Maternal),用正则表达式会更灵活。比如可以匹配所有()里的内容,或者指定只提取(Paternal)或(Maternal)里的内容:

using System.Text.RegularExpressions;

String fammedhistory= "High Blood Pressure(Paternal), Reproductive Disease(Maternal)";
// 匹配所有()内的内容(非贪婪匹配,避免跨括号)
MatchCollection matches = Regex.Matches(fammedhistory, @"\(([^)]+)\)");
foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[1].Value);
    // 输出结果:
    // Paternal
    // Maternal
}

// 如果只想提取特定的(Paternal)或(Maternal),可以用更精准的正则
Match specificMatch = Regex.Match(fammedhistory, @"High Blood Pressure\((Paternal|Maternal)\)");
if (specificMatch.Success)
{
    String specificResult = specificMatch.Groups[1].Value;
    // specificResult的值是"Paternal"
}

这样不管字符串里有多少个括号,都能精准拿到你需要的内容啦!

内容的提问来源于stack exchange,提问作者Zcy Cortejo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:14:09