Ashley Ashley - 3 months ago 9
C# Question

Find a string between 2 known values

I need to be able to extract a string between 2 tags for example: "00002" from "

morenonxmldata<tag1>0002</tag1>morenonxmldata
"

I am using C# and .NET 3.5.

Answer

A RegEx-free solution:

string ExtractString(string s, string tag) {
     // You should check for errors in real-world code, omitted for brevity
     var startTag = "<" + tag + ">";
     int startIndex = s.IndexOf(startTag) + startTag.Length;
     int endIndex = s.IndexOf("</" + tag + ">", startIndex);
     return s.Substring(startIndex, endIndex - startIndex);
}