一个字符串如:str = "<p>依据季节变化和茶树新梢生长的间歇<a href='#?id=2008'>年份2008</a>平常清明过后春茶开始大</p>"
我现在只想找到非html代码中的2008,并高亮显示,效果如下:
str = "<p>依据季节变化和茶树新梢生长的间歇<a href='#?id=2008'>年份<label class='sr_word01'>2008</label></a>平常清明过后春茶开始大</p>"如果用 str..Replace("2008","<label class='sr_word01'>2008</label>") 就会把链接地址的参数id=2008中的2008也替换掉了。如何才能实现?请高手指点

解决方案 »

  1.   

    Function ReplaceTest( strPatrn, ItemInfo )
    Dim regEx
    Dim str
    Dim patrnArry
    Dim patrn
    Dim replStr
    Dim nRTCount
    Dim nArrayCount

    str = ""
    patrn  = ""
    replStr = ""
    nArrayCount = 1

    patrnArry = split( strPatrn, " " )

    For nRTCount = 0 To UBound( patrnArry )
    If IsEmptyString( Trim( patrnArry( nRTCount ) ) ) = false Then
    replStr = replStr & "<font color='red'>$" & nArrayCount & "</font>"
    nArrayCount = nArrayCount + 1
    End If
    Next

    For nRTCount = 0 To UBound( patrnArry )
    If IsEmptyString( Trim( patrnArry( nRTCount ) ) ) = false Then
    patrn =  patrn & "(" &Trim( patrnArry( nRTCount ) ) & ")|"
    End If
    Next

    patrn = mid( patrn, 1, len( patrn ) - 1 )

    Set regEx = New RegExp  
    regEx.Pattern = patrn
    regEx.IgnoreCase = True
    regEx.Global = True
    ReplaceTest = regEx.Replace(ItemInfo, replStr)

    End Function
      

  2.   


    #region 返回搜索红色关键词 replacered
        public static string replacered(string title, string redkey)
        {
            title = title.Replace(redkey, "<font color='#ff0000'>" + redkey + "</font>");
            return title;
        }
        #endregion<%# Member.replacered(Eval("aAbout").ToString(),keyword) %>
      

  3.   

    有没有C#的,VB的我看不懂,谢谢了
      

  4.   

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <a href='#?id=2008' id="a1">年份2008</a>
        <script>
        document.getElementById("a1").innerHTML=document.getElementById("a1").innerHTML.replace("2008","<font color='red'>2008</font>");
        </script>
        </div>
        </form>
    </body>
    </html>
      

  5.   

    不是只有一处。我再详细说一下吧
    一个文章阅读的网站,要搜索包含关键字的文章,并高亮显示关键字。
    因为文章中包含有html代码,有可能在html代码中也包含这个关键字,
    因此搜索 加高亮的时候不能给<...>中的关键字加高亮
      

  6.   

    我刚做好这个效果
    http://search.rrsou.com/search.aspx?k=%e8%a3%85%e4%bf%ae&p=1
      

  7.   

    我再详细说一下吧 
    一个文章阅读的网站,要搜索包含关键字的文章,并高亮显示关键字。 
    因为文章中包含有html代码,有可能在html代码中也包含这个关键字, 
    因此搜索 加高亮的时候不能给 <...>中的关键字加高亮 
      

  8.   

    我搜索的高亮不是你说的,那我新闻系统的高亮是不是你说的那种啊
    http://www.rrsou.com/news.aspx?id=7679&page=1
      

  9.   

    你搜索出来的都转成纯文本了,我要的是含有html的内容
      

  10.   

    我再详细说一下吧 
    一个文章阅读的网站,要搜索包含关键字的文章,并高亮显示关键字。 
    因为文章中包含有html代码,有可能在html代码中也包含这个关键字, 
    因此搜索 加高亮的时候不能给 <...>中的关键字加高亮 
      

  11.   

    你说的那种情况,我觉得可以先把"<p>依据季节变化和茶树新梢生长的间歇 <a href='#?id=2008'>年份 <label class='sr_word01'>2008 </label> </a>平常清明过后春茶开始大 </p>"替换成"##1依据季节变化和茶树新梢生长的间歇 ##2年份 ##32008 ##4 ##5平常清明过后春茶开始大 ##6"然后你用replace来转换最后再把##1 ##2 ##3....恢复过来,之前先用正则把html代码<....>都找出来放在一个string数组里能看明白吧.
      

  12.   

    其实我也有种方法,知道思路,不知道该怎么写,大家帮忙看下
    不用replace方法了,而是循环查找关键字,找到一个,先判断离它最近的一个<或>,
    如果它后面第一个符号是<,就高亮显示,要是>就不做处理
      

  13.   

        string AV2Color(string tmpStr)
        {
            string reValue = tmpStr;
            string xingcheng = @"([a-zA-Z]{6}&nbsp;)";
            reValue = Regex.Replace(reValue, xingcheng, "<font color=yellow>$1</font>");
        }
      

  14.   

    >任意内容关键字任意内容<
    这个字符串可以用正则表示出来吗?
      

  15.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
    <title>Untitled Document</title>
    <style type="text/css">
    <!--
    .adKeyword {
     color: #FF0000;
    }
    -->
    </style>
    </head>
    <body>
    <a href='#?id=2008'>年份 <label class='sr_word01'>2008 </label> </a>
    </body>
    </html>
    <script language="JavaScript" type="text/javascript"><!--
    if(document.createRange){
     var range = document.createRange();
    }else
     var range = document.body.createTextRange(); 
     
    if(range.findText){ while(range.findText("2008"))
     {
      range.pasteHTML(range.text.fontcolor("red"));
      range.collapse(true);
     }
    }else{ 
     var s,n;
     s = window.getSelection();
     
     
     while(window.find("2008"))
     {
      var n = document.createElement("SPAN");
      n.style.color="red" 
      s.getRangeAt(0).surroundContents(n);
     }
     
     
    }
    //--></script>js或者用正则替换,这是js例子
      

  16.   

    本人赞同用正则表达式解决这个问题,只要搜索到“>[N个字符]2008”,就可以替换掉楼主想要的,具体的字符串模型不是很清楚。好像是">\s2008",呵呵 
      

  17.   

    正则可以用这样的 string s = "<a href='#?id=2008'>年份 <label class='sr_word01'>2008 </label> </a>"; 
    string r = @"(>[ \s\S]*)(2008)([ \s\S]*<)"; 
    string v = Regex.Replace(s, r, "$1<font color=red>$2</font>$3"); 
    Response.Write(v);
      

  18.   

    用js吧 这里推荐给你个高亮jquery plugin
    http://hi.baidu.com/freezesoul/blog/item/75b05166b197c920ab184cb7.html
      

  19.   

    http://blog.csdn.net/kongwei521/archive/2008/03/03/2142799.aspx我转载的一篇文章
    你看看符合不符合你。
      

  20.   

    看了一下上面说的,有些根本不理解楼主的意思,特别是写方法的那些。楼主我给你提供个思路吧,这个算法比较麻烦,可以简单一点你想替换的字符串s,替换时查找一下离他最近的符号“>”和“<”,看一下哪个靠后,如果"<"这个在后面,此时的字符串s不要替换反之可以替换。这是大体思路,这样有漏洞,你可以根据这个思路慢慢解决现存的漏洞吧。
      

  21.   

    一个苕办法
    str..Replace("2008</a>"," <label class='sr_word01'>2008 </label></a>") 
      

  22.   

    我晕,怎么结了....命苦...
    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false"%><!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:TextBox ID="TextBox1" runat="server" Height="101px" TextMode="MultiLine" Width="312px">一个字符串如:str = &quot; &lt;p&gt;依据季节变化和茶树新梢生长的间歇 &lt;a href='#?id=2008'&gt;年份2008 &lt;/a&gt;平常清明过后春茶开始大 &lt;/p&gt;&quot;
    我现在只想找到非html代码中的2008,并高亮显示,效果如下:
    str = &quot; &lt;p&gt;依据季节变化和茶树新梢生长的间歇 &lt;a href='#?id=2008'&gt;年份 &lt;label class='sr_word01'&gt;2008 &lt;/label&gt; &lt;/a&gt;平常清明过后春茶开始大 &lt;/p&gt;&quot;如果用 str..Replace(&quot;2008&quot;,&quot; &lt;label class='sr_word01'&gt;2008 &lt;/label&gt;&quot;) 就会把链接地址的参数id=2008中的2008也替换掉了。如何才能实现?请高手指点</asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server">2008</asp:TextBox>&nbsp;
            <hr />
            <asp:Literal ID="Literal1" runat="server"></asp:Literal>
            <br />
            <asp:TextBox ID="TextBox3" runat="server" Height="101px" TextMode="MultiLine" Width="312px"></asp:TextBox><br />
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
        </form>
    </body>
    </html>
    using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Text.RegularExpressions;public partial class _Default : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {    }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //Reg(TextBox1.Text, TextBox2.Text);        string input = TextBox1.Text;
            string regStr = TextBox2.Text;        MatchCollection matches = null;
            string temp = protectHtml(input, ref matches);
            temp = Reg(temp, regStr);
            Literal1.Text = TextBox3.Text = restoreHtml(temp, matches);
        }    private string Reg(string input, string replace)
        {
            //设置高亮样式
            string replaceformat = "<span style=\"font-size:14px; font-weight:bold; color:#f00; background-color:#ff0\">{0}</span>";
            Regex reg = new Regex(String.Format("{0}", replace), RegexOptions.Multiline);
            return reg.Replace(input, string.Format(replaceformat, replace));
        }    /// <summary>
        /// 设置各个html部分为自定义标号
        /// </summary>
        /// <param name="input">输入内容</param>
        /// <param name="matches">匹配集合</param>
        /// <returns>替换的字串</returns>
        private string protectHtml(string input, ref MatchCollection matches)
        {
            //匹配html的正则
            Regex htmlReg =
                new Regex(@"\<.*?\>", RegexOptions.Multiline);
            //获取匹配集合
            matches = htmlReg.Matches(input);
            //设置替换字串
            string Format = "[[{0}]]";
            //替换html,记录位置
            for (int i = 0; i < matches.Count;i++ )
            {
                input = input.Replace(matches[i].Value, string.Format(Format, i));
            }
            return input;
        }    /// <summary>
        /// 将标号恢复html
        /// </summary>
        /// <param name="input">高亮设置好的字串</param>
        /// <param name="matches">匹配集合</param>
        /// <returns>最终字串</returns>
        private string restoreHtml(string input, MatchCollection matches)
        {
            //设置替换字串
            string Format = "[[{0}]]";
            for (int i = 0; i < matches.Count; i++)
            {
                input = input.Replace(string.Format(Format, i), matches[i].Value);
            }
            return input;
        }
    }
      

  23.   


    <html>
        <head>
            <title>IE Range Example</title>
            <script type="text/javascript">
                function useRanges() {
                    var oRange = document.body.createTextRange();
                    var oP1 = document.getElementById("p1");
                    oRange.findText("Hello");
                    oRange.pasteHTML("<em>Howdy</em>");
                }
            </script>
        </head>
        <body><p id="p1"><b>Hello</b> World</p>
            <input type="button" value="Use Ranges" onclick="useRanges()" />  
            <p><strong>Note:</strong> This example uses Internet Explorer ranges and will only work on Internet Explorer.</p>
          
        </body>
    </html>
      

  24.   

    <script>
    window.onload=function(){
       document.body.innerHTML=document.body.innerHTML.replace(/\2008/g,"<font color='red'>2008</font>");
    }
    </script><body>
    ...
    ...
    ...
    </body>
      

  25.   

    我的这个函数对单关键词没有什么问题,多关键词还有一点遗漏的
    private static string HLSearchWords(string word)
    /// ----分析keyword,空格分离
    {
    word = Regex.Replace(word, @"(\"")|(\()|(\))|(\+)|(\|)|(-)|(“)|(”)|(()|())|(+)|(-)|(\\)|(\*)|(\<)|(\>)|( )", " ");
    /*word = word.Replace("(", " ");
    word = word.Replace(")", " ");
    word = word.Replace("-", " ");
    word = word.Replace("|", " ");*/
    word = Regex.Replace(word, @"\s+", " ");
    return word.Trim();
    }
    public static string HLTextDisplay(string strWord, string strSource)
    {
    strSource = System.Text.RegularExpressions.Regex.Replace(strSource, @"<\w+[^<>]*>|<\/\w+[^<>]*>", "");
    strSource = System.Text.RegularExpressions.Regex.Replace(strSource, "\r\n", @"<br>");
    if (strWord==null || strWord.Length==0) return strSource;
    strWord = HLSearchWords(strWord);
    string strTemp=strSource;
    strWord = "(" + Regex.Replace(strWord, @"\s+", ")|(") + ")";
    strTemp = Regex.Replace(strTemp, strWord, "<font color=color:#00c>$&</font>", RegexOptions.IgnoreCase);
    return strTemp;
    }
      

  26.   

    写个js脚本的,用的Prototype的$$,试了一下: var lnk = $$('a[href*="2008"]')[0];  
    var str = lnk.innerHTML;
    var a = str.match('([\u4e00-\u9fa5]+)2008');
    if(a.length > 1)
    {
    a = a[1];
    str = a + "<span style='color:red'>" + 2008 + "</span>";
    lnk.innerHTML = str;
    }
      

  27.   

    看了一些现有网站,把搜索内容关键字在搜索列表中高亮显示都是在关键字所在位置加个标签,css 对此标签进行样式处理。
      

  28.   

    是这种得嘛?
    http://www.codefan.net/s/search.aspx?q=%e6%af%95%e4%b8%9a
      

  29.   

    这用得是 Lucene.net2.0 的 HighLighterhttp://www.codefan.net/s/search.aspx?q=%e6%af%95%e4%b8%9a
      

  30.   

    str.Replace("2008<"," <label class='sr_word01'>2008 </label>") 
    用这试试
      

  31.   

    Regex.Replace就可以了 可以忽略大小写
      

  32.   


    //没开编译器,伪代码供参考
    var year= 2008;
    str = "<p>依据季节变化和茶树新梢生长的间歇<a href='#?id=2008'>年份"+year+"</a>平常清明过后春茶开始大</p>"str = str.Replace(year+"</a>","<label class='sr_word01'>"+year+"</label></a>");  
      

  33.   

    引用 11 楼 wzy_love_sly 的回复:
    HTML code<html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
    <title>无标题页</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <a href='#?id=2008' id="a1">年份2008</a>
    <script>
    document.getElementById("a1").innerHTML=document.getElementById("a1").innerHTML.replace("2008","<font color='red'>2008</font>");
    </script>
    </div>

    不是只有一处。
    用js裏面的repalceall不就可以全部替換掉了
      

  34.   

    在后台弄打个比方 你要搜索 title 字段里的 关键词 word当你从数据库 把数据查询出来后 在后台进行操作if (uword.Length > 0)
        ds.Tables[0].Rows[i]["title"] = ds.Tables[0].Rows[i]["title"].ToString().Replace(uword, string.Format("<span class=\"red\">{0}</span>", uword));前台绑定的时候<a href="..."><%# Eval("title")%></a>遍可以了
      

  35.   


    忘了告诉你 是循环替换for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    {
      //替换
    }