![](/img/trans.png)
[英]How do i grab everything inside the BODY html tag (From a string) using RegEx Asp.net C#
[英]Asp.Net C# Html String Preview using Regex
我有一個字符串預覽類,該類從數據庫中獲取一個HTML字符串,或者只是普通的舊html字符串,並輸出x個字符的預覽。一會兒 如果有人可以幫助我。
我最關心的特定部分是獲得x個字符,但計數中不包含標簽,但也不殺死標簽。
如果有人閱讀過任何東西或代碼復雜的東西,我將很樂意。
任務很簡單,我的朋友……聽起來像是一個有趣的老板。
void Main()
{
string test = "<html>wowzers description: none <div>description:a1fj391</div></html>";
string result = getFirstChars(test, 15);
Console.WriteLine(result);
//result: wowzers descrip
}
static Regex MyRegex = new Regex(
"(?<tag></?\\s*\\w+\\s*>*)",
RegexOptions.Compiled);
static string getFirstChars(string html, int count)
{
string nonTagText = MyRegex.Replace(html,"");
return nonTagText.Substring(0, count);
}
如果您想保留標簽...則可以這樣做:
void Main()
{
string test = "<html><b>wowzers</b> description: none <div>description:a1fj391</div></html>";
string result = getFirstChars(test, 15);
Console.WriteLine(result);
//result: <html><b>wowzers</b> descrip
}
static Regex MyRegex = new Regex(
"(?<tag></?\\s*\\w+\\s*>)(?<content>[^<]*)",
RegexOptions.Compiled);
static string getFirstChars(string html, int count)
{
int totalCount = 0;
int contentCount = 0;
foreach(Match match in MyRegex.Matches(html))
{
contentCount += match.Groups["content"].Length;
totalCount += match.Length;
if(contentCount >= count)
{
totalCount -= contentCount - count;
break;
}
}
return html.Substring(0, totalCount);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.