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

后端 未结 17 1775
鱼传尺愫
鱼传尺愫 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:35

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

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

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 15:42
    int start = input.IndexOf("(") + 1;
    int length = input.IndexOf(")") - start;
    output = input.Substring(start, length);
    
    0 讨论(0)
提交回复
热议问题