Marco
Marco

Reputation: 91

Taking part of string based on multiple delimiters?

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?

Upvotes: 3

Views: 137

Answers (4)

John Ryann
John Ryann

Reputation: 2393

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

Upvotes: 0

Sean Hosey
Sean Hosey

Reputation: 323

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

Upvotes: 1

usr
usr

Reputation: 171178

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

Upvotes: 1

L.B
L.B

Reputation: 116108

Regex can help here

string input = "abc(def)ghi";
var def = Regex.Match(input, @"\((.+?)\)").Groups[1].Value;

Upvotes: 7

Related Questions