216
//int idxEnd = s.LastIndexOf(to, idxStart); //produces unexpected results 1 when to="a" and idxStart=1 when from="a", we expect last last index of string "aaaa" which is 4-1=3
1
using System;using System.Diagnostics;
2
3
namespace GetBetweenStrings_Blog
4
{
5
public static class Extensions
6
{
7
/// <summary>
8
/// Get a substring between two anchor strings, maximal span
9
/// </summary>
10
/// <param name="s">source string</param>
11
/// <param name="from">search from end of this string</param>
12
/// <param name="to">to beginning of this string, searching backwards, from end to start of s</param>
13
/// <returns>a substring between from and to, maximal span</returns>
14
public static string GetFirstStringBetweenStringsCleanup(this string s, string from, string to)
15
{
16
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(from) || string.IsNullOrEmpty(to)) return string.Empty;
17
18
int idxFrom = s.IndexOf(from);
19
int idxStart = idxFrom + from.Length; //we filter "not found" -1, never get neg number here
20
21
if (idxFrom == -1 || idxStart >= s.Length - 1)
22
return string.Empty;
23
24
int idxEnd = s.LastIndexOf(to);
Cached Result