Follow @endyourif rss Facebook LinkedIn

String Extract Extension Method with C# String Extract Extension Method with C#

Published on Jun 15, 2022

The following extension method is probably one of my all time favorite things to do with strings: parse out text between a start and end delimiter. I like it so much I actually created a StringExtractComponent for CakePHP for it back in 2009!

Now let's take what we learned there and apply this to C#.



The idea behind the function is to provide a string with a piece of text that defines the beginning of where you want to extract the text followed by an ending string. The function will pull out the text between those two delimiters but not include them in the results.


using System;

namespace Common.Extensions
{
public static class StringExtensions
{
/// <summary>
/// Extract a value from the string between a start and end message.
/// </summary>
/// <param name="value"></param>
/// <param name="startString"></param>
/// <param name="endString"></param>
/// <returns></returns>
public static string Extract(this string value, string startString, string endString)
{
var startPos = value.IndexOf(startString) + startString.Length;
var length = value.IndexOf(endString, startPos) - startPos;

return value.Substring(startPos, length);
}
}
}


To use this code you apply it to a string, e.g.


var myMainString = "This has some HTML data that I want to parse out <span>My magic text</span>";
var spanString = myMainString.Extract("<span>", "</span>");


The variable spanString will contain: My magic text. So happy to reveal a C# version of this function that I loved so much back in my PHP days!

Tags: ASP.NET MVC and Web API Tutorial | extension | extract

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP