ASP.NET Forums
首页 搜索 用户列表 FAQ 注册 登录  
ASP.NET Forums » .Net 专区 » 英文原稿 » Highlighting Multiple Search Keywords in ASP.NET
  Highlighting Multiple Search Keywords in ASP.NET
帖子发起人: venjiang   发起时间: 2006-3-14 9:56 PM   回复数: 1
« 上一主题 下一主题 »
楼主
  2006-3-14, 9:56 PM
venjiang 离线,最后访问时间: 8/29/2008 11:09:38 PM venjiang



发帖数前10位

超级管理员
职务: 超级管理员
参谋长
等级: 参谋长
注册: 2004年6月8日
区域: 中国河北
积分: 2,096
精华: 9
发贴: 1,489

ASP NET Forums2.0 中文版开发团队
  Highlighting Multiple Search Keywords in ASP.NET
 

Highlighting Multiple Search Keywords in ASP.NET
By Dimitrios Markatos
Published: 12/1/2005
Reader Level: Beginner Intermediate

Introduction

A few years ago I had written a short article that demonstrated how one could highlight a keyword within a DataGrid control based on what was passed into it. Although this functionality served its purpose, it was however limited to one search word at a time; multiple search terms didn't apply. Since then I needed to find out a way to actually highlight multiple key words no matter where they were in the text.

As a result, I came up with a method, again using the ever handy regular expressions that allows the user the ability to highlight multiple keywords within any given body of text, including any web controls. In this example, however, the main player we'll be using is the MatchEvaluator Delegate method. Delegates are simply very useful function pointers that handle the operation using various approaches. Moreover, they do not contain nor define any real functional code, but rather assign the function that is to be used in its place. And this is what will allow us such functionality.

So before we get into the inner workings, I have listed the entire page code in both C# and VB, so readers have the ability to use their native language code without any unnecessary conversion on their part. So cut and paste the appropriate section of code and give it a spin.

The Entire Code

<%@ Page Language="C#" Debug="False" Strict="True" Explicit="True" Buffer="True"%>
<%@ Import Namespace="System" %>

<html>
<head>
<title>Highlighting Multiple Search Keywords in .NET</title>
</head>

<style type="text/css">
.highlight {text-decoration:none; font-weight:bold; color:black; background:yellow;}
</style>

<body bgcolor="#FFFFFF" topmargin="0" marginheight="0" onLoad="document.forms[0].keywords.focus();">

<script language="C#" runat="server">

void Page_Load(Object Source, EventArgs E)
{

LabelTxt.Text = "This sample text is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter.";

}

public string Highlight(string Search_Str, string InputTxt)
{

// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

// Highlight keywords by calling the delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));

// Set the RegExp to null.
RegExp = null;

}

public string ReplaceKeyWords(Match m)
{

return "<span class=highlight>" + m.Value + "</span>";

}

</script>

<H3>Highlighting Multiple Search Keywords in .NET</H3><BR>

<form runat="server" method="post">

<asp:TextBox id="keywords" runat="server"/>
<asp:Button id="button" Text="Submit" runat="server" /><br><br>
<asp:Label id="LabelTxt" runat="server"/>

</form>

<%= Highlight(keywords.Text, LabelTxt.Text)%>

</body>
</html>

<%@ Page Language="VB" Debug="False" Strict="True" Explicit="True" Buffer="True"%>
<%@ Import Namespace="System" %>

<html>
<head>
<title>Highlighting Multiple Search Keywords in .NET</title>
</head>

<style type="text/css">
.highlight {text-decoration:none; font-weight:bold; color:black; background:yellow;}
</style>

<body bgcolor="#FFFFFF" topmargin="0" marginheight="0" onLoad="document.forms[0].keywords.focus();">

<script language="vb" runat="server">

Sub Page_Load(Source As Object, E As EventArgs)

LabelTxt.Text = "This sample text is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter."

End Sub

Public Function Highlight (Search_Str As String, InputTxt As String) As String

' Setup the regular expression and add the Or operator.
Dim RegExp As Regex = New Regex(Search_Str.Replace (" ", "|").Trim(), RegExOptions.IgnoreCase)

' Highlight keywords by calling the MatchEvaluator delegate each time a keyword is found.
Highlight = RegExp.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceKeyWords))

' Set the Regex to nothing.
RegExp = Nothing

End Function

Public Function ReplaceKeyWords(ByVal m As Match) As String

Return "<span class=highlight>" & m.Value & "</span>"

End Function

</script>

<BR><H3>Highlighting Multiple Search Keywords in .NET</H3><BR>

<form runat="server" method="post">

<asp:TextBox id="keywords" runat="server"/>
<asp:Button id="button" Text="Submit" runat="server" /><br><br>
<asp:Label id="LabelTxt" runat="server" Visible="False"/>

</form>

<%= Highlight(keywords.Text, LabelTxt.Text)%>

</body>
</html>

Highlighting Multiple Keywords

To begin, the Highlight() function here, as in my earlier article, still uses Regular Expressions. In this example, I've added a search textbox, a submit button and a label containing some arbitrary sample text that will be searched, by calling and Response.Writing the Highlight() function, and return us our results.

<%= Highlight(keywords.Text, LabelTxt.Text)%>

The Highlight() function, in this example, accepts only two parameters: Search_Str - which are the words to be searched for, and InputTxt - the text to be searched.

public string Highlight(string Search_Str, string InputTxt) {}

Thus, in order to accommodate multiple word searching, we'll need the regular expression "Or" character operator which is represented by a pipe symbol "|" or vertical bar, to be placed between each word entered in the search box. For example, entering the text "sample multiple text any " in the search box would call the highlight function, and replace all empty spaces in between each word with a pipe symbol and end up looking like this "sample|multiple|text|any".

Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegExOptions.IgnoreCase);

Once this occurs, our search terms are ready to be evaluated and processed by our Highlight function's MatchEvaluator Delegate that is called into operation every time the certain keyword string is found within our searchable text, and replaces the matched keyword with the result of the called delegate function, as listed below.

return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));

Accordingly, the called delegate function ReplaceKeyWords() listed below grabs the value of the regular expression match (m.Value), wraps the highlight style sheet around it, and returns it back to our Highlight() function that replaces the matched keyword within the searchable text.

public string ReplaceKeyWords(Match m)
{

return "<span class=highlight>" + m.Value + "</span>";

}

So as a result, in example, by entering the terms "sample multiple text any " in the search box, and hitting submit, the Highlight() function would search the paragraph below.

This sample text is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter.

And return it back looking like so:

This sample text is used to demonstrate multiple keyword highlighting in .NET. Simply type in any word or words found within this sample text and hit the submit button to highlight the searched words. Also, it doesn't matter how many you enter.

One quick note, the regular expression object instantiated above will match the keywords anywhere in the text. In the example above notice how we were looking for the word "any", but the word "many" got highlighted as well, and this is the magic of regular expressions. However, there are instances when this ambiguity is unnecessary. So to circumvent this type of behavior, simply replace the Highlight function's RegEx object with the appropriate one listed below.

Regex RegExp = new Regex("\\b" + Search_Str.Replace(" ", "\\b|\\b").Trim() + "\\b", RegexOptions.IgnoreCase);

Dim RegExp As Regex = New Regex("\b" & Search_Str.Replace (" ", "\b|\b").Trim() & "\b", RegExOptions.IgnoreCase)

The "\b" added above is one of the few Atomic Zero-Width Assertion metacharacters that allows you the flexibility in limiting the results, for a more precise match. Also notice the "RegexOptions" Enumeration is case sensitive in C#.

In addition, as in my previous article, the aforementioned techniques could again be applied to a DataGrid control with ease and allow for a more powerfully featured DataGrid. Implementing this is easily done by simply wrapping the Highlight() function around any data column you wish to search and provide the search keywords, as shown below, and that's it. You'll now end up with that column displaying your search words, but highlighted now.

<asp:DataGrid runat="server" id="SearchResults" AutoGenerateColumns="False">
 <Columns>
  <asp:TemplateColumn>
   <ItemTemplate>
   <%# Highlight(KeyWords, DataBinder.Eval(Container.DataItem, "Data column to be searched"))) %>
   </ItemTemplate>
  </asp:TemplateColumn>
 </Columns>
</asp:DataGrid>

Conclusion

There are many different Regular Expression Language Elements that can be customized to modify, create and parse all kinds of strings. All in all, I hope this was a useful read, where you're now able to add this functionality to your projects and display more informative and detailed results to your user.

Until next time. Happy .NETing </>


IP 地址: 已登录   来自: 已登录    返回顶部
第 2 楼
  2008-8-26, 9:18 AM
tianhong 离线,最后访问时间: 8/26/2008 9:23:00 AM tianhong

发帖数前500位

士兵
等级: 士兵
注册: 2008年8月26日
积分: 10
精华: 0
发贴: 10
tianhong
 
天虹上海翻译公司是国内数一数二的上海翻译公司信誉良好的上海翻译公司急你所急,专业的上海翻译公司
先祝大家新年快乐!!2008年工作顺利!!我公司招聘翻译长年有效招聘专兼职翻译:招聘翻译,专业翻译服务:翻译网址上海翻译公司翻译公司英语翻译日语翻译韩语翻译英语口译法语翻译德语翻译俄语翻译。天虹翻译公司服务项目:日语翻译英语翻译韩语翻译德语翻译法语翻译俄语翻译意大利语翻译西班牙语翻译阿拉伯语翻译葡萄牙语翻译翻译价格英文翻译中文中文翻译日文日文翻译中文英语口译同声传译等。翻译交流可进入翻译论坛,欢迎发帖。
天虹上海翻译公司,专业高质量翻译服务.欢迎咨询,公司网址:http://www.tianhongsh.com

IP 地址: 已登录   来自: 已登录    返回顶部
 第 1 页 总共 1 页 [共有 2 条记录]
ASP.NET Forums » .Net 专区 » 英文原稿 » Highlighting Multiple Search Keywords in ASP.NET

友情链接: hiDotNet官方论坛 | hiDotNet知识库 | 其它友情链接

Asp.Net Forums version: 2.5.2725
(C)Copyright 2004-2007, hiDotNet.com. All Rights Reserved.
意见反馈 | 关于我们

Powered by Community Server :: Forums 中文本地化: hiDotNet.com