![](/img/trans.png)
[英]Regex to capture groups of parentheses including inner and outer parentheses
[英]Use Regex to remove outer parentheses from nested expression, but leave inner parentheses?
我正在努力找出一個好的正則表達式,該正則表達式的值應為:
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#中的第一組括號嗎?
如果您只想處理一個級別,那就沒問題了。
@"\((?:\([^()]*\)|[^()])*\)"
要么
如果您不想匹配外部括號。
@"(?<=\()(?:\([^()]*\)|[^()])*(?=\))"
這是我在評論中提到的非正則表達式解決方案,假設您的場景與您布置的一樣簡單:
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);
嘗試使用不使用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);
}
您將需要對其進行清理。 做一些錯誤檢查。 該函數假定:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.