jason jason - 3 months ago 7
C# Question

Read a rest of the string by a substring

I have a string like this :

string mystring = "No : 123 - Date : 07/06/2009 - Explanation : Some explanation text"


I want to get Some explanation text from this string. How can I code get the rest of the string after Explanation : in C#? Or is there a better way to get that substring? Thanks.

Answer

I would recommend a Regex approach here, it would remove the issues from other posts where the :character could be included in the explanation string.

This example would solve the issue as long the "Explanation :" tag is always at the end of the string and the "Explanation :" text can not appear inside the Some explanation text.

var mystring = "No : 123 - Date : 07/06/2009 - Explanation : Some explanation text"
var regex = new Regex("(.*)Explanation :(.*)");
var match = regex.Match(mystring);

if (match.Success)
{
   var explanation =  match.Groups[match.Groups.Count - 1].Value;
}