简体   繁体   English

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

[英]Use Regex to remove outer parentheses from nested expression, but leave inner parentheses?

I'm working on figuring out a good regular expression that would take a value such as: 我正在努力找出一个好的正则表达式,该正则表达式的值应为:

Transformer Winding Connections (Wye (Star) or Delta)

and would match: 并会匹配:

Wye (Star) or Delta

What I have so far is: 到目前为止,我有:

      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 is returning: valueMatch返回:

(Wye (Star) or Delta)

Is there some clever way to only remove the first set of parentheses in C#? 有什么聪明的方法可以只删除C#中的第一组括号吗?

If you want to deal with only one level then this would be fine. 如果您只想处理一个级别,那就没问题了。

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

or 要么

If you don't want to match the outer paranthesis. 如果您不想匹配外部括号。

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

DEMO DEMO

Here's the non-regex solution I mentioned in a comment, assuming your scenario is as simple as you laid out: 这是我在评论中提到的非正则表达式解决方案,假设您的场景与您布置的一样简单:

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

Try this function, which doesn't use RegEx: 尝试使用不使用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);
}

You'll want to clean it up a bit. 您将需要对其进行清理。 Do some error checking. 做一些错误检查。 The functions assumes: 该函数假定:

  1. The string has parenthesis 字符串带有括号
  2. The parenthesis are balanced 括号是平衡的
  3. The string isn't null 字符串不为空

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM