String Extract Extension Method with C# 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!

Published on Jun 15, 2022

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

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.