您的位置:首页 > 其它

使用正则表达式实现搜索关键字高亮显示

2009-12-21 21:47 1206 查看
下面通过一个小例子讲解一下在网页开发中,如何实现关键字检索之后的高亮显示。我们使用到的技术是正则表达式的替换功能

1.页面源文件

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="WebApplication5._Default"%>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:Literalrunat="server"ID="lb"></asp:Literal>
<hr/>
<asp:Buttonrunat="server"ID="submit"Text="搜索"onclick="submit_Click"/>
</div>
</form>
</body>
</html>
2.代码源文件
usingSystem;

usingSystem.Text.RegularExpressions;

namespaceWebApplication5
{
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
if(!IsPostBack){
lb.Text="ares@xizhang.com555ares@microsoft.com";
}
}

protectedvoidsubmit_Click(objectsender,EventArgse)
{
stringtemp=lb.Text;
lb.Text=Regex.Replace(temp,@"[\w\.=-]+@[\w\.-]+\.[\w]{2,3}",c=>{returnstring.Format("<spanstyle='background-color:yellow'>{0}</span>",c);});

}
}
}


.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}

3.测试效果





点击“搜索”按钮




.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐