我正在努力找出一个好的正则表达式,它会带来如下值:
Transformer Winding Connections (Wye (Star) or Delta)
并匹配:
Wye (Star) or Delta
到目前为止我所拥有的是:
string longName = "Transformer Winding Connections (Wye (Star) or Delta)";
// Match everything until first parentheses
Regex nameRegex = new Regex(@"([^(]*)");
Match nameMatch = nameRegex.Match(longName);
// Match everything from first parentheses on
Regex valueRegex = new Regex(@"\(.+\)");
Match valueMatch = valueRegex.Match(longName);
valueMatch正在返回:
(Wye (Star) or Delta)
是否有一些聪明的方法只能删除C#中的第一组括号?
答案 0 :(得分:2)
如果你只想处理一个级别,那就没关系了。
@"\((?:\([^()]*\)|[^()])*\)"
或
如果你不想匹配外部的paranthesis。
@"(?<=\()(?:\([^()]*\)|[^()])*(?=\))"
答案 1 :(得分:0)
这是我在评论中提到的非正则表达式解决方案,假设您的方案与您的方案一样简单:
string longName = "Transformer Winding Connections (Wye (Star) or Delta)";
int openParenIndex = longName.IndexOf("(");
int closingParenIndex = longName.LastIndexOf(")");
if (openParenIndex == -1 || closingParenIndex == -1
|| closingParenIndex < openParenIndex)
{
// unexpected scenario...
}
string valueWithinFirstLastParens = longName.Substring(openParenIndex + 1,
closingParenIndex - openParenIndex - 1);
答案 2 :(得分:0)
尝试此功能,该功能不使用RegEx:
private static string RemoveOuterParenthesis(string str)
{
int ndx = 0;
int firstParenthesis = str.IndexOf("(", StringComparison.Ordinal);
int balance = 1;
int lastParenthesis = 0;
while (ndx < str.Length)
{
if (ndx == firstParenthesis)
{
ndx++;
continue;
}
if (str[ndx] == '(')
balance++;
if (str[ndx] == ')')
balance--;
if (balance == 0)
{
lastParenthesis = ndx;
break;
}
ndx++;
}
return str.Remove(firstParenthesis, 1).Remove(lastParenthesis - 1, 1);
}
你会想要清理一下。做一些错误检查。这些函数假定: