问题描述:

比如说 string[] 中有 “上海”“北京”“天津”"abc"
目标字符串为 "上海在北京和天津的<br >南边<a href="#">ddd</a>"

统一替换为"<a>上海</a>在<a>北京</a>和<a>天津</a>的<br >南边<a href="#">ddd</a>"


Highlighting Multiple Search Keywords in ASP.NET
By Dimitrios Markatos
Published: 12/1/2005
Reader Level: Beginner Intermediate
Rated: 4.71 by 7 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

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 </>

posted on 2007-09-13 10:20  罗明超  阅读(258)  评论(0)    收藏  举报