Click here to Skip to main content
15,900,973 members
Articles / Web Development / HTML
Alternative
Tip/Trick

General string parsing techniques

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
1 Nov 2011CPOL 5.1K  
namespace ParseTests{ using System; using System.Collections.Generic; using System.Text.RegularExpressions; public static class ExtensionMethods { /// /// Extracts text from a source string that is between two specified tags. ...
C#
namespace ParseTests
{
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;

    public static class ExtensionMethods
    {
        /// <summary>
        /// Extracts text from a source string that is between two specified tags.  
        /// Tags can be included by setting 'includeTokens' to true.
        /// </summary>
        /// <param name="source">String to be searched.</param>
        /// <param name="startToken">String that
        ///    identifies the beginning of a match.</param>
        /// <param name="endToken">String that identifies
        ///    the end of a match.</param>
        /// <param name="includeTokens">Value indicating
        ///     whether to include tokens.</param>
        /// <returns>Text between the start and end tokens.</returns>
        public static IEnumerable<string> GetBetween(
            this string source,
            string startToken,
            string endToken,
            bool includeTokens = false)
        {
            string pattern = string.Format(
                "(?:{0})(.*?)(?:{1})",
                Regex.Escape(startToken),
                Regex.Escape(endToken));

            Match match = Regex.Match(source, pattern, RegexOptions.Singleline);

            while (match.Success)
            {
                yield return includeTokens ? match.Value : match.Groups[1].Value;
                match = match.NextMatch();
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Insight Global
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --