Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract text that lies between parentheses (round brackets)?

Tags:

c#

.net

regex

People also ask

How do I extract text between parentheses brackets in Excel?

To extract the text between any characters, use a formula with the MID and FIND functions. The FIND Function locates the parenthesis and the MID Function returns the characters in between them.

How do I extract text between parentheses in Word?

SEARCH(")",A2)-SEARCH("(",A2)-1: The position of the right parentheses subtracts the position of the left parentheses to get the number of the characters between the parentheses that need to be extracted. And this returned value will be recognized as the num_chars argument in the MID function.


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

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"

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

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