Get string between two strings in a string

前端 未结 23 2182
别跟我提以往
别跟我提以往 2020-11-22 09:46

I have a string like:

\"super exemple of string key : text I want to keep - end of my string\"

I want to just keep the string which is betw

相关标签:
23条回答
  • 2020-11-22 10:47
    string input = "super exemple of string key : text I want to keep - end of my string";
    var match = Regex.Match(input, @"key : (.+?)-").Groups[1].Value;
    

    or with just string operations

    var start = input.IndexOf("key : ") + 6;
    var match2 = input.Substring(start, input.IndexOf("-") - start);
    
    0 讨论(0)
  • 2020-11-22 10:48

    As I always say nothing is impossible:

    string value =  "super exemple of string key : text I want to keep - end of my string";
    Regex regex = new Regex(@"(key \: (.*?) _ )");
    Match match = regex.Match(value);
    if (match.Success)
    {
        Messagebox.Show(match.Value);
    }
    

    Remeber that should add reference of System.Text.RegularExpressions

    Hope That I Helped.

    0 讨论(0)
  • 2020-11-22 10:49

    You already have some good answers and I realize the code I am providing is far from the most efficient and clean. However, I thought it might be useful for educational purposes. We can use pre-built classes and libraries all day long. But without understanding the inner-workings, we are simply mimicking and repeating and will never learn anything. This code works and is more basic or "virgin" than some of the others:

    char startDelimiter = ':';
    char endDelimiter = '-';
    
    Boolean collect = false;
    
    string parsedString = "";
    
    foreach (char c in originalString)
    {
        if (c == startDelimiter)
             collect = true;
    
        if (c == endDelimiter)
             collect = false;
    
        if (collect == true && c != startDelimiter)
             parsedString += c;
    }
    

    You end up with your desired string assigned to the parsedString variable. Keep in mind that it will also capture proceeding and preceding spaces. Remember that a string is simply an array of characters that can be manipulated like other arrays with indices etc.

    Take care.

    0 讨论(0)
  • 2020-11-22 10:50

    A working LINQ solution:

    string str = "super exemple of string key : text I want to keep - end of my string";
    string res = new string(str.SkipWhile(c => c != ':')
                               .Skip(1)
                               .TakeWhile(c => c != '-')
                               .ToArray()).Trim();
    Console.WriteLine(res); // text I want to keep
    
    0 讨论(0)
  • 2020-11-22 10:50

    Since the : and the - are unique you could use:

    string input;
    string output;
    input = "super example of string key : text I want to keep - end of my string";
    output = input.Split(new char[] { ':', '-' })[1];
    
    0 讨论(0)
提交回复
热议问题