Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Text between tags

Tags:

c#

regex

Hey I have an input string that looks like this:

Just a test Post [c] hello world [/c] 

the output should be:

hello world

can anybody help?

I tried to use:

Regex regex = new Regex("[c](.*)[/c]");
var v = regex.Match(post.Content);
string s = v.Groups[1].ToString();
like image 296
Dean Avatar asked Dec 03 '22 00:12

Dean


1 Answers

You may do this without Regex. Consider this extension method:

public static string GetStrBetweenTags(this string value, 
                                       string startTag, 
                                       string endTag)
{
    if (value.Contains(startTag) && value.Contains(endTag))
    {
        int index = value.IndexOf(startTag) + startTag.Length;
        return value.Substring(index, value.IndexOf(endTag) - index);
    }
    else
        return null;
}

and use it:

string s = "Just a test Post [c] hello world [/c] ";
string res = s.GetStrBetweenTags("[c]", "[/c]");
like image 104
horgh Avatar answered Dec 28 '22 17:12

horgh