Returns the part of the string between the first occurrence of the opening Text and the FIRST occurrence - CSharp System

CSharp examples for System:String SubString

Description

Returns the part of the string between the first occurrence of the opening Text and the FIRST occurrence

Demo Code


using System;//  w ww  .ja  v  a 2 s  .  c  o m

public class Main{
        /// <summary>
        /// Returns the part of the string between the first occurrence of the openingText and the FIRST occurrence of the closingText, 
        /// or null when the original text does not contain the opening and/or closing text.
        /// </summary>
        public static string BetweenNonGreedy(this string originalText, string openingText, string closingText)
        {
            if (String.IsNullOrEmpty(originalText) || !(originalText.Contains(openingText) && originalText.AfterFirst(openingText).Contains(closingText)))
            {
                return null;
            }

            return originalText.AfterFirst(openingText).BeforeFirst(closingText);
        }
        /// <summary>
        /// Returns the part of the string before the first occurrence of the given string,
        /// or null when the original text does not contain the text to find. 
        /// </summary>
        public static string BeforeFirst(this string originalText, string textToFind)
        {
            if (String.IsNullOrEmpty(originalText) || !originalText.Contains(textToFind))
            {
                return null;
            }

            return originalText.Substring(0, originalText.IndexOf(textToFind, StringComparison.Ordinal));
        }
        /// <summary>
        /// Returns the part of the string after the first occurrence of the given string, 
        /// or null when the original text does not contain the text to find.
        /// </summary>
        public static string AfterFirst(this string originalText, string textToFind)
        {
            if (String.IsNullOrEmpty(originalText) || !originalText.Contains(textToFind))
            {
                return null;
            }
            
            return originalText.Substring(originalText.IndexOf(textToFind, StringComparison.Ordinal) + textToFind.Length);
        }
}

Related Tutorials