![](/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.