3

I have a string with parentheses and I wish to extract only the portion of the string inside the parentheses.

For example, from the following string:

"abc(def)ghi"

I'd like to get "def", with no parentheses.

I have done some searching but the closest thing I've found so far is String.Split():

string s = "3,2,4,5,6";
string[] words = s.Split(',');

But String.Split only takes 1 delimiter at a time. Is there a better way to grab only the string inside the parentheses?

Steve Howard
  • 6,737
  • 1
  • 26
  • 37
Marco
  • 91
  • 1
  • 1
  • 3

4 Answers4

7

Regex can help here

string input = "abc(def)ghi";
var def = Regex.Match(input, @"\((.+?)\)").Groups[1].Value;
L.B
  • 114,136
  • 19
  • 178
  • 224
1

You can split on multiple chars: s.Split("()".ToCharArray()). Not sure whether that is the right solution for you, or a regex is.

usr
  • 168,620
  • 35
  • 240
  • 369
1

You can pass in an array of chars to split on.

Like so:

string s = "abc(def)ghi";
char[] chars = new char[] { '(', ')' };
string[] parts = s.Split(chars);
Sean Hosey
  • 323
  • 1
  • 7
  • It will split the string whenever a character matches one of the characters in the char-array. No matter in which order they are entered (both in the array and in the string to be split). – ThoBa Sep 26 '13 at 20:28
  • if you expecting parts[0] to be "abc", parts[1] to be "def" and parts[2] to be "ghi" then - yes - it would - just like ThoBa stated. – Sean Hosey Sep 26 '13 at 20:28
  • @L.B if you expect it to be the same result as `abc(def)ghi`, yes. – Tim S. Sep 26 '13 at 20:29
0

Just another alternative. Simple, double split

        string s = "abc(def)ghi";
        string []first = s.Split('(');
        string[] second = first[1].Split(')');
        Console.WriteLine(second[0]);
        Console.ReadLine();
John Ryann
  • 2,283
  • 11
  • 43
  • 60