下面通过一个小例子讲解一下在网页开发中,如何实现关键字检索之后的高亮显示。我们使用到的技术是正则表达式的替换功能
1. 页面源文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication5._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal runat="server" ID="lb"></asp:Literal>
<hr />
<asp:Button runat="server" ID="submit" Text="搜索" onclick="submit_Click"/>
</div>
</form>
</body>
</html>
2. 代码源文件
using System;
using System.Text.RegularExpressions;
namespace WebApplication5
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
lb.Text = "ares@xizhang.com 555 ares@microsoft.com";
}
}
protected void submit_Click(object sender, EventArgs e)
{
string temp = lb.Text;
lb.Text = Regex.Replace(temp, @"[\w\.=-]+@[\w\.-]+\.[\w]{2,3}", c => { return string.Format("<span style='background-color:yellow'>{0}</span>", c); });
}
}
}
3. 测试效果
点击“搜索”按钮