简体   繁体   English

正则表达式仅匹配 Div 中的第一个段落标记

[英]Regular Expression to match only first Paragraph tag in Div

I want to match first empty P tag for each DIV and insert some text.我想为每个 DIV 匹配第一个空 P 标签并插入一些文本。 I am using (<p[^>]*>)(</p>) this regular expression which is matching to all P tags inside DIV.我正在使用(<p[^>]*>)(</p>)这个正则表达式,它与 DIV 中的所有 P 标签匹配。

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.注意:我们没有使用任何 HTML 文件进行解析。 Its only a few strings.它只有几根弦。

we can acheive using HTMLAgilityPack.我们可以使用 HTMLAgilityPack 来实现。

Code Explanation: Creating a instance of HTMlDocument and load the html string .代码说明:创建 HTMlDocument 实例并加载 html 字符串。 Selecting the first node from given string and inserting text for paragraph tag with innerHTML.从给定的字符串中选择第一个节点并为带有 innerHTML 的段落标记插入文本。 If no need to create or save document, we can directly use OuterHtml to see output.如果不需要创建或保存文档,我们可以直接使用 OuterHtml 来查看输出。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM