使用正则表达式从嵌套表达式中删除外括号,但是留下内括号?

时间:2015-07-21 18:21:49

标签: c# .net regex

我正在努力找出一个好的正则表达式,它会带来如下值:

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#中的第一组括号?

3 个答案:

答案 0 :(得分:2)

如果你只想处理一个级别,那就没关系了。

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

如果你不想匹配外部的paranthesis。

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

DEMO

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

你会想要清理一下。做一些错误检查。这些函数假定:

  1. 该字符串具有括号
  2. 括号是平衡的
  3. 字符串不为空