正则表达式匹配div标签之间的内容 [英] Regex to match content between div tag

查看:324
本文介绍了正则表达式匹配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

推荐答案

我没有''让你的意图从代码中反映出来。在我看来,就像你以相反的方式使用东西一样,所以我很好奇Match方法如何替换你的东西。



RegexOptions.Multiline [ ^ ]含义:

I didn''t got your intentions reflecting from the code. It seems to me, like you use things in the opposite way, so I am pretty curious how does the Match method replace something for you.

See RegexOptions.Multiline[^] meaning:
引用:

多线模式。更改^和


的含义,使它们分别在任何行的开头和结尾匹配,而不仅仅是整个字符串的开头和结尾。
so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire string.



您需要单行



请查看以下代码,更通用的解决方案:


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标签之间的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆