1

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:

(Wye (Star) or Delta)

Is there some clever way to only remove the first set of parentheses in C#?

Raymond
  • 77
  • 9

3 Answers3

2

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

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

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);
Sven Grosen
  • 5,616
  • 3
  • 30
  • 52
0

Try this function, which doesn't use 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
Icemanind
  • 47,519
  • 50
  • 171
  • 296