0

我想以这样一种方式更改我的下面的正则表达式, 如果 在 aspx 页面中找到它,它不应该替换/删除。然后跳过以替换为空白字符

下面的表达式工作正常,但唯一的问题是它删除了所有 字符。

在我的 aspx 代码中,我<span class='clscode'>&nbsp;</span>用这种类型的标记内部文本编写了&nbsp;字符。

这是我的 C# 代码。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Linq;
using System.Text.RegularExpressions;
public partial class TestPage : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 /// my code 
 }

    private static readonly Regex t = new Regex(@">\s+<", RegexOptions.Compiled);
    private static readonly Regex lb = new Regex(@"\n\s+", RegexOptions.Compiled);
    protected override void Render(HtmlTextWriter writer)
    {
        using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
        {
            base.Render(htmlwriter);
            string html = htmlwriter.InnerWriter.ToString();
            html = t.Replace(html, "> <");
            html = lb.Replace(html, string.Empty);
            writer.Write(html.Trim());
        }
    }
}

我需要以下类型的输出。例如:我的页面有很多这是一个测试示例

<div id="dvtest"> <space> <space> <space>
<span>&nbsp;</span><space> <space>
<div id='test2'> sample &nbsp;&nbsp;text&nbsp;    </div></div>

//... 喜欢这个标签。我需要这样的输出。

<div id="dvtest"><span>&nbsp;</span><div id='test2'>sample &nbsp;&nbsp;text&nbsp;</div></div>

注意:这里<space>表示空格不可见字符

4

2 回答 2

0
protected override void Render(HtmlTextWriter writer)
{
    using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
    {
        string re1 = "( )";
        base.Render(htmlwriter);
        string html = htmlwriter.InnerWriter.ToString();
        Regex r = new Regex(re1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match m = r.Match(html);
        if (m.Success)
        {
            String c1 = m.Groups[1].ToString();

            html = html.Replace(c1.ToString(), "");

            writer.Write(html);

            // Console.Write("(" + c1.ToString() + ")" + "\n");
        }


    }
}
于 2014-01-31T09:04:14.403 回答
0

像这样试试

如果您不能使用面向 HTML 解析器的解决方案来过滤掉标签,这里有一个简单的正则表达式。

string noHTML = Regex.Replace(inputHTML, @"\n$", "").Trim();

Regex Demo

于 2014-01-31T08:57:47.240 回答