271

I have a string User name (sales) and I want to extract the text between the brackets, how would I do this?

I suspect sub-string but I can't work out how to read until the closing bracket, the length of text will vary.

1
  • 2
    Show us what you've tried. Have you looked at using regular expressions? Dec 18, 2008 at 16:37

19 Answers 19

539

If you wish to stay away from regular expressions, the simplest way I can think of is:

string input = "User name (sales)";
string output = input.Split('(', ')')[1];
4
  • 104
    Honestly, this should've been selected as the answer. Jan 11, 2013 at 18:58
  • 2
    Isn't it be further contracted into input.Split("()".ToCharArray())[1] May 12, 2014 at 9:55
  • 20
    and in case u want to use the same logic to select multiple: var input = "(fdw) User name (sales) safdsdf (again?)"; var output = input.Split('(', ')').Where((item, index) => index % 2 != 0).ToList();
    – WtFudgE
    Apr 25, 2016 at 10:36
  • Note that this answer doesn't cover cases like: string input = "User name )WrongValue(sales)". It will return WrongValue
    – elshev
    Oct 16, 2023 at 9:26
492

A very simple way to do it is by using regular expressions:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

As a response to the (very funny) comment, here's the same Regex with some explanation:

\(             # Escaped parenthesis, means "starts with a '(' character"
    (          # Parentheses in a regex mean "put (capture) the stuff 
               #     in between into the Groups array" 
       [^)]    # Any character that is not a ')' character
       *       # Zero or more occurrences of the aforementioned "non ')' char"
    )          # Close the capturing group
\)             # "Ends with a ')' character"
2
  • 562
    I love it when people say "a simple way is to use regular expressions" and then offer what amounts to a string of indecipherable hieroglyphics (it's especially fun when different people suggest regex and each comes up with a different set of hieroglyphics for the same problem). :)
    – Deltics
    Mar 26, 2010 at 3:14
  • 1
    THANK YOU for your explanation of the Regex string....I'm with the previous commenter in that I haven't mastered the concepts of Regex. You've helped tremendously. Again, THANK YOU!
    – BluJ IT
    Mar 23, 2023 at 18:27
98

Assuming that you only have one pair of parenthesis.

string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
0
26

Use this function:

public string GetSubstringByString(string a, string b, string c)
{
    return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}

and here is the usage:

GetSubstringByString("(", ")", "User name (sales)")

and the output would be:

sales
0
18

Regular expressions might be the best tool here. If you are not famililar with them, I recommend you install Expresso - a great little regex tool.

Something like:

Regex regex = new Regex("\\((?<TextInsideBrackets>\\w+)\\)");
string incomingValue = "Username (sales)";
string insideBrackets = null;
Match match = regex.Match(incomingValue);
if(match.Success)
{
    insideBrackets = match.Groups["TextInsideBrackets"].Value;
}
0
16
string input = "User name (sales)";

string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
2
  • 2
    You should of course only calculate the location of the first bracket once. Dec 18, 2008 at 19:29
  • In the case where you have inner parenthesis e.g. input = "User name (sales(1)) you may want to use input.LastIndexOf(')') which will work if there are inner parenthesis or not.
    – Ben
    Jan 5, 2015 at 10:30
15

A regex maybe? I think this would work...

\(([a-z]+?)\)
1
  • It fails when there is nested parenthesis, check this demo. Jan 27 at 15:02
8
using System;
using System.Text.RegularExpressions;

private IEnumerable<string> GetSubStrings(string input, string start, string end)
{
    Regex r = new Regex(Regex.Escape(start) +`"(.*?)"`  + Regex.Escape(end));
    MatchCollection matches = r.Matches(input);
    foreach (Match match in matches)
    yield return match.Groups[1].Value;
}
7
int start = input.IndexOf("(") + 1;
int length = input.IndexOf(")") - start;
output = input.Substring(start, length);
4

Use a Regular Expression:

string test = "(test)"; 
string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
Console.WriteLine(word);
3
 var input = "12(34)1(12)(14)234";
 var output = "";
 for (int i = 0; i < input.Length; i++)
 {
     if (input[i] == '(')
     {
         var start = i + 1;
         var end = input.IndexOf(')', i + 1);
         output += input.Substring(start, end - start) + ",";
     }
 }

 if (output.Length > 0) // remove last comma
  output = output.Remove(output.Length - 1);

output : "34,12,14"

2
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
2

The regex method is superior I think, but if you wanted to use the humble substring

string input= "my name is (Jayne C)";
int start = input.IndexOf("(");
int stop = input.IndexOf(")");
string output = input.Substring(start+1, stop - start - 1);

or

string input = "my name is (Jayne C)";
string output  = input.Substring(input.IndexOf("(") +1, input.IndexOf(")")- input.IndexOf("(")- 1);
0
1

Here is a general purpose readable function that avoids using regex:

// Returns the text between 'start' and 'end'.
string ExtractBetween(string text, string start, string end)
{
  int iStart = text.IndexOf(start);
  iStart = (iStart == -1) ? 0 : iStart + start.Length;
  int iEnd = text.LastIndexOf(end);
  if(iEnd == -1)
  {
    iEnd = text.Length;
  }
  int len = iEnd - iStart;

  return text.Substring(iStart, len);
}

To call it in your particular example you can do:

string result = ExtractBetween("User name (sales)", "(", ")");
1

I'm finding that regular expressions are extremely useful but very difficult to write. So, I did some research and found this tool that makes writing them so easy.

Don't shy away from them because the syntax is difficult to figure out. They can be so powerful.

1
  • 4
    Welcome to SO! This is good advice, but it shouldn't have been posted as an answer. General advice like this should be posted as comments, if at all. An answer must address the asker's specific problem. I know you don't have enough reputation points to post comments yet, but this is exactly why the rep threshold exists. When you've been around a little longer you'll see that people are always recommending tools like Rubular (in comments, of course). In other words, this advice may be useful, but it's not urgent.
    – Alan Moore
    Feb 18, 2015 at 15:11
1

This code is faster than most solutions here (if not all), packed as String extension method, it does not support recursive nesting:

public static string GetNestedString(this string str, char start, char end)
{
    int s = -1;
    int i = -1;
    while (++i < str.Length)
        if (str[i] == start)
        {
            s = i;
            break;
        }
    int e = -1;
    while(++i < str.Length)
        if (str[i] == end)
        {
            e = i;
            break;
        }
    if (e > s)
        return str.Substring(s + 1, e - s - 1);
    return null;
}

This one is little longer and slower, but it handles recursive nesting more nicely:

public static string GetNestedString(this string str, char start, char end)
{
    int s = -1;
    int i = -1;
    while (++i < str.Length)
        if (str[i] == start)
        {
            s = i;
            break;
        }
    int e = -1;
    int depth = 0;
    while (++i < str.Length)
        if (str[i] == end)
        {
            e = i;
            if (depth == 0)
                break;
            else
                --depth;
        }
        else if (str[i] == start)
            ++depth;
    if (e > s)
        return str.Substring(s + 1, e - s - 1);
    return null;
}
1
  • 1
    works best for me because it handles nesting Jan 3, 2023 at 18:12
1

I've been using and abusing C#9 recently and I can't help throwing in Spans even in questionable scenarios... Just for the fun of it, here's a variation on the answers above:

var input = "User name (sales)";
var txtSpan = input.AsSpan();
var startPoint = txtSpan.IndexOf('(') + 1;
var length = txtSpan.LastIndexOf(')') - startPoint;
var output = txtSpan.Slice(startPoint, length);

For the OP's specific scenario, it produces the right output. (Personally, I'd use RegEx, as posted by others. It's easier to get around the more tricky scenarios where the solution above falls apart).

A better version (as extension method) I made for my own project:

//Note: This only captures the first occurrence, but 
//can be easily modified to scan across the text (I'd prefer Slicing a Span)  
public static string ExtractFromBetweenChars(this string txt, char openChar, char closeChar)
{
    ReadOnlySpan<char> span = txt.AsSpan();
    int firstCharPos = span.IndexOf(openChar);
    int lastCharPos = -1;

    if (firstCharPos != -1) 
    { 
        for (int n = firstCharPos + 1; n < span.Length; n++)
        {
            if (span[n] == openChar) firstCharPos = n; //This allows the opening char position to change
            if (span[n] == closeChar) lastCharPos = n;
            if (lastCharPos > firstCharPos) break;
            //This would correctly extract "sales" from this [contrived]
            //example: "just (a (name (sales) )))(test"
        }
        return span.Slice(firstCharPos + 1, lastCharPos - firstCharPos - 1).ToString();
    }
    return "";
}
2
  • This is my vote seeing as how using Span will result in the best performance for such a scenario.
    – Maximus
    Sep 24, 2021 at 13:43
  • @Maximus who said it has better performance? Feb 20 at 17:17
0

Much similar to @Gustavo Baiocchi Costa but offset is being calculated with another intermediate Substring.

int innerTextStart = input.IndexOf("(") + 1;
int innerTextLength = input.Substring(start).IndexOf(")");
string output = input.Substring(innerTextStart, innerTextLength);
-1

I came across this while I was looking for a solution to a very similar implementation.

Here is a snippet from my actual code. Starts substring from the first char (index 0).

 string separator = "\n";     //line terminator

 string output;
 string input= "HowAreYou?\nLets go there!";

 output = input.Substring(0, input.IndexOf(separator)); 
1
  • 2
    This doesn't answer what the OP has asked.
    – dicemaster
    Jul 12, 2018 at 11:34