Reputation: 9610
I need to extract of subset of a String using a pair of markers that would be contained within it. For example, given the following String:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<!--extract-->
Sed nec luctus magna, ac tincidunt metus. Maecenas sodales iaculis ipsum sed blandit.<!--/extract-->
Quisque tincidunt nulla sapien, non faucibus turpis aliquam at.
How can I extract everything in between and (but not the tags themselves)? The String will be different lengths every time, but will always contain the markers.
I've been messing with String.SubString()
but am struggling to reliably calculate the start/end indexes. Note that the start/end markers will always have specific values to allow them to be located.
Thanks in advance.
Upvotes: 0
Views: 107
Reputation: 1526
this code will help you achive your requirement
string s="adipiscing elit.<!--extract-->Sed nec luct<!--/extract-->"
string p = "<!--extract-->";
string q = "<!--/extract-->";
int a = s.IndexOf("<!--extract-->");
int b = s.IndexOf("<!--/extract-->");
string result= s.Substring(a + p.Length, b - (a + p.Length));
Upvotes: 1
Reputation: 1055
I always find it easier to Substring
twice when trimming from both sides of a desired string
string myString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <!--extract-->Sed nec luctus magna, ac tincidunt metus. Maecenas sodales iaculis ipsum sed blandit.<!--/extract--> Quisque tincidunt nulla sapien, non faucibus turpis aliquam at.";
myString = myString.Substring(myString.IndexOf("<!--extract-->") + "<!--extract-->".Length);
myString = myString.Substring(0, myString.IndexOf("<!--/extract-->"));
Or, to do the same in one call (uglier)
string myString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <!--extract-->Sed nec luctus magna, ac tincidunt metus. Maecenas sodales iaculis ipsum sed blandit.<!--/extract--> Quisque tincidunt nulla sapien, non faucibus turpis aliquam at.";
myString = myString.Substring(myString.IndexOf("<!--extract-->") + "<!--extract-->".Length, myString.IndexOf("<!--/extract-->") - myString.IndexOf("<!--extract-->") - "<!--extract-->".Length);
Upvotes: 1