Get string between two strings in a string

前端 未结 23 2507
别跟我提以往
别跟我提以往 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:29

    or, with a regex.

    using System.Text.RegularExpressions;
    
    ...
    
    var value =
        Regex.Match(
            "super exemple of string key : text I want to keep - end of my string",
            "key : (.*) - ")
        .Groups[1].Value;
    

    with a running example.

    You can decide if its overkill.

    or

    as an under validated extension method

    using System.Text.RegularExpressions;
    
    public class Test
    {
        public static void Main()
        {
            var value =
                    "super exemple of string key : text I want to keep - end of my string"
                        .Between(
                            "key : ",
                            " - ");
    
            Console.WriteLine(value);
        }
    }
    
    public static class Ext
    {
        static string Between(this string source, string left, string right)
        {
            return Regex.Match(
                    source,
                    string.Format("{0}(.*){1}", left, right))
                .Groups[1].Value;
        }
    }
    

提交回复
热议问题