我的 ASP.NET Web 应用程序中有一个文本区域,用于输入 html 代码。现在还有一个按钮控件,单击它应该只检索放置在文本框中某些 html 标记之间的文本。
例如:
1) 用户输入包括标签等的 html 代码,然后单击“确定”按钮
2)在我的代码中,文本区域的文本被检索并且只有 <p></p>
之间的部分标记应保存到字符串对象。
我显然可以从文本区域获取文本并将其附加到字符串对象,但我无法弄清楚如何只获取某个 html 标记内的文本,如 <p></p>
.有人可以帮帮我吗?
最佳答案
试试这个...示例取自 MSDN并略作修改以显示您的情况:
using System;
using System.Text.RegularExpressions;
class Example
{
static void Main()
{
string text = "start <p>I want to capture this</p> end";
string pat = @""<p>((?:.|\r|\n)+?)</p>"";
// Instantiate the regular expression object.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match"+ (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group"+i+"='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
}
}
m = m.NextMatch();
}
}
}
您可以在 ideone.com 上看到实际效果.
如果你想包含你的 <p>
结果中的标记,然后只需将正则表达式中括号的位置更改为:
string pat = @"(<p>(?:.|\r|\n)+?</p>)";
关于c# - 从C#中的文本框获取html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3627279/