簡體   English   中英

使用正則表達式從嵌套表達式中刪除外部括號,但保留內部括號嗎?

[英]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#中的第一組括號嗎?

如果您只想處理一個級別,那就沒問題了。

 @"\((?:\([^()]*\)|[^()])*\)"

要么

如果您不想匹配外部括號。

@"(?<=\()(?:\([^()]*\)|[^()])*(?=\))"

DEMO

這是我在評論中提到的非正則表達式解決方案,假設您的場景與您布置的一樣簡單:

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);
}

您將需要對其進行清理。 做一些錯誤檢查。 該函數假定:

  1. 字符串帶有括號
  2. 括號是平衡的
  3. 字符串不為空

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM