Monday, May 29, 2017

Replace string between html tag using regex

 
 
//This method is used to replace the string between html tag by given string including html tag

//There is no need to find index position of StartTag or EndTag. Therefore no chances to raise the any exception

//Replace string if starting and ending is exist

// If you missed end bracket of html tag(>), it will append it self.

public static string ReplaceStringBetweenHTMLTag(string Content, string StartTag, string EndTag, string StrReplace)

{

string StrPattern = string.Empty;

if (StartTag != string.Empty)

{

if (StartTag.Contains(">"))

StrPattern = string.Format("{0}.*?{1}", StartTag, EndTag);

else

StrPattern = string.Format("{0}.*?>.*?{1}", StartTag, EndTag);

Content = Regex.Replace(Content, StrPattern, StrReplace);

}
}
 
Example1:
Content = " Rest of the Content.cboxIE #cboxT After Style type ";
StartTag= ""
EndTag = ""
StrReplace ="blog------- "
Result:
blog------- After Style type

Example2:

Content = "// StartTag= "EndTag = ""
StrReplace ="
blog------- "
Result:
blog------- After Style
 

No comments:

Post a Comment