-1

I want to match first empty P tag for each DIV and insert some text. I am using (<p[^>]*>)(</p>) this regular expression which is matching to all P tags inside DIV.

var yourDivString = "<DIV WITH Paragraph Tag(s) and many other tags>";
yourDivString = Regex.Replace(yourDivString , "(<p[^>]*>)(</p>)", "THIS IS FIRST EMPTY P TAG in EACH DIV")

Example:

<div>
    <p></p>
    <p></p>
</div>

Excepted Output:

<div>
    <p>THIS IS FIRST EMPTY P TAG in EACH DIV</p>
    <p></p>
</div>

Note: we are not using any HTML files to parse. Its only a few strings.

PavanKumar GVVS
  • 859
  • 14
  • 45

1 Answers1

0

we can acheive using HTMLAgilityPack.

Code Explanation: Creating a instance of HTMlDocument and load the html string . Selecting the first node from given string and inserting text for paragraph tag with innerHTML. If no need to create or save document, we can directly use OuterHtml to see output.

using HtmlAgilityPack;

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(yourString);
var p = doc.DocumentNode.SelectSingleNode("//p");
p.InnerHtml = "THIS IS FIRST EMPTY P TAG in EACH DIV";
yourString = doc.DocumentNode.OuterHtml;
Console.WriteLine(yourString);
PavanKumar GVVS
  • 859
  • 14
  • 45