Get string between two strings in a string

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

    Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:

    public static class StringExtensions {
        /// 
        /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
        /// 
        /// a string
        /// an optional string to search after
        /// an optional string to search before
        /// an optional comparison for the search
        /// a substring based on the search
        public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
        {
            var fromLength = (from ?? string.Empty).Length;
            var startIndex = !string.IsNullOrEmpty(from) 
                ? @this.IndexOf(from, comparison) + fromLength
                : 0;
    
            if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }
    
                var endIndex = !string.IsNullOrEmpty(until) 
                ? @this.IndexOf(until, startIndex, comparison) 
                : @this.Length;
    
            if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }
    
            var subString = @this.Substring(startIndex, endIndex - startIndex);
            return subString;
        }
    }
    
    // usage:
    var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
    // returns " to keep "
    

提交回复
热议问题