String Extract Extension Method with C#


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’ve also created two other examples with SQL substring between two characters SQL substring between two characters as well as a StringExtractComponent for CakePHP.

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

The way this extension method is implemented is very similar to how I did the C# Truncate String Extension. 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 or learn how to convert date with C#.

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!

About the author

By Jamie

My Books