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

后端 未结 17 1740
鱼传尺愫
鱼传尺愫 2020-11-22 15:12

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

相关标签:
17条回答
  • 2020-11-22 15:25

    Use a Regular Expression:

    string test = "(test)"; 
    string word = Regex.Match(test, @"\((\w+)\)").Groups[1].Value;
    Console.WriteLine(word);
    
    0 讨论(0)
  • 2020-11-22 15:26
    string input = "User name (sales)";
    
    string output = input.Substring(input.IndexOf('(') + 1, input.IndexOf(')') - input.IndexOf('(') - 1);
    
    0 讨论(0)
  • 2020-11-22 15:32

    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)); 
    
    0 讨论(0)
  • 2020-11-22 15:33

    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 讨论(0)
  • 2020-11-22 15:33

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

    \(([a-z]+?)\)
    
    0 讨论(0)
  • 2020-11-22 15:34

    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.

    0 讨论(0)
提交回复
热议问题