[英]Get html tags from textbox in C#
我的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>)";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.