[英]Asp.Net C# Html String Preview using Regex
I got a string preview class which takes a Html string from the database or just plain old html string and outputs a preview of x characters.... Now my boss asked me to convert it into regex, and I been striking a wall for a while now. 我有一个字符串预览类,该类从数据库中获取一个HTML字符串,或者只是普通的旧html字符串,并输出x个字符的预览。一会儿 If anyone can help me with that.
如果有人可以帮助我。
The specific part that mostly concerns me is getting x characters without including tags in the count but not killing the tags either. 我最关心的特定部分是获得x个字符,但计数中不包含标签,但也不杀死标签。
I would love if anyone has anything i read on or a codeplex thing. 如果有人阅读过任何东西或代码复杂的东西,我将很乐意。
The task is simple my friend... sounds like an interesting boss. 任务很简单,我的朋友……听起来像是一个有趣的老板。
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);
}
if you want to keep tags... then you could do this: 如果您想保留标签...则可以这样做:
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.