Gets all the instances of a string that are between to substrings. - CSharp System

CSharp examples for System:String SubString

Description

Gets all the instances of a string that are between to substrings.

Demo Code

// file, You can obtain one at http://www.apache.org/licenses/
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;/*from   w w  w  . jav a2  s .c o  m*/

public class Main{
        /// <summary>
		/// Gets all the instances of a string that are between to substrings.
		/// E.g. "Hello {0}, how are you today {1}".Betweens("{", "}") will return ["0", "1"]
		/// </summary>
		/// <param name="search"></param>
		/// <param name="prefix"></param>
		/// <param name="suffix"></param>
		/// <returns></returns>
		public static List<string> Betweens(this string search, string prefix, string suffix) {
			List<string> output = new List<string>();

			int posA = search.IndexOf(prefix);
			while (posA > -1) {
				posA += prefix.Length;
				int posB = search.IndexOf(suffix, posA);
				if (posB > posA) {

					output.Add( search.Substring(posA, posB - posA));
				}
				if (posB + suffix.Length + 1 >= search.Length) {
					break;
				}
				posA = search.IndexOf(prefix, posB + suffix.Length+ 1);
			}
			return output;

		}
}

Related Tutorials