本文介绍了正则表达式匹配div标签之间的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好
我想获得带有特定类名的div标签之间的内容,并希望将其替换为其他内容。
目前我正在使用以下模式:
Hi All
I want to get content between div tag with specific class name and want to replace it with another content.
Currently I am using following pattern:
string _pattern = @"\s*(.+?)\s*";
string _headPattern = string.Format("<div class=\"headercontent\">{0}</div>", _pattern);
Match _match = Regex.Match(_htmlString, _headPattern, RegexOptions.Multiline);
工作正常如果我在div标签中有以下内容。
Its working fine if I have following content in div tag.
<div class="headercontent">{lastname}</div>
但它没有关注内容。
But it fails for following content.
<div class="headercontent">{firtname}
{lastname}</div>
如果div内容中有新行,则它失败了。
谢谢
Imrankhan
If there is a new line in div content then it fails.
Thanks
Imrankhan
推荐答案
引用:
多线模式。更改^和
您需要单行
。
请查看以下代码,更通用的解决方案:
You need Singleline
instead.
Please look at the following code for a possible, more general solution:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
class HtmlPatterFiller
{
Regex re;
string globalPattern;
public HtmlPatterFiller(string className)
{
globalPattern = String.Format("<div[^>]*?class=([\"'])[^>]*{0}[^>]*\\1[^>]*>(.*?)</div>",className);
re = new Regex(globalPattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
public string Fill(string html, Dictionary<string,string> dictionary)
{
return re.Replace(html, delegate(Match m) {
var res = m.Value;
foreach(var e in dictionary)
{
res = res.Replace(e.Key, e.Value);
}
return res;
});
}
}
class Program
{
public static void Main()
{
string input = @"User full name:<div id='d1' class=""c1 c2"">
Fn:<span class=""fn"">{FirstName}</span><br />
LN:<span class=""ln"">{LastName}</span>
</div>";
var filler = new HtmlPatterFiller("c1");
var d = new Dictionary<string, string>() { {"{FirstName}", "John"}, {"{LastName}", "Smith"} };
Console.WriteLine(filler.Fill(input, d));
}
}
这篇关于正则表达式匹配div标签之间的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!