Search code examples
c#substring

Get substring including the brackets C#


  • I have an excel file where I get 2 strings, one without brackets and one with brackets. While i can fetch the data if I am aware of the start and end word like in the below first string example are 'string' and 'fetch' respectively.

  • The second string comes with bracket anywhere in between the letters hence i cannot predict the index of the brackets. When I give the startWord as 'string' and endword as 'fetch' I want the code to work by including the bracket and get everything in between just like the firstString example.

  • The below is the code I am using which is perfectly running for firstString. Need help in secondString output.

         string startWord = "string";
         string endWord = "fetch";
         string firstString = "the string i want to fetch is this";
         string secondString = "the strin{9.6}g i want{6.2} to fet{5.2}ch is this";
    
         int pFrom = firstString.ToLower().IndexOf(startWord) + startWord.Length;
         int pTo = firstString.ToLower().IndexOf(endWord, pFrom);
    
         string firstStringOutput = firstString.Substring(pFrom, pTo - pFrom).Trim(); // current output I am getting i want to
         //string secondStringExpextedOutput = "i want{6.2} to"; // the output I want including the brackets for secondString
    

Any help would be greatly appreciated, thanks in advance.


Solution

  • Let's give Regex a chance.

    var pattern1 = string.Concat(startWord.Select(x => x + @"({\d\.\d})*"));
    var pattern2 = string.Concat(endWord.Select(x => x + @"({\d\.\d})*"));
    
    var m1 = Regex.Match(secondString, pattern1);
    var m2 = Regex.Match(secondString, pattern2);
    
    int from = m1.Index + m1.Length;
    int to = m2.Index;
    
    string secondStringOutput = secondString[from..to].Trim();