在搜索词substring的索引处插入

时间:2014-03-27 13:01:59

标签: c# regex asp.net-mvc

我正在尝试突出显示结果中的搜索字词。通常它可以根据SO上找到的代码here正常工作。我的问题是它用搜索项替换子字符串,即在这个例子中它将替换" LOVE"用"爱" (不可接受的)。所以我想我可能想找到子串开头的索引,做一个INSERT的开头< span>标记,并在子字符串的末尾执行类似操作。由于yafs可能很长,我还认为我需要将stringbuilder集成到这里。这是可行的,还是有更好的方法?一如既往,请提前感谢您的建议。

string yafs = "Looking for LOVE in all the wrong places...";
string searchTerm = "love";

yafs = yafs.ReplaceInsensitive(searchTerm, "<span style='background-color: #FFFF00'>" 
+  searchTerm + "</span>");

3 个答案:

答案 0 :(得分:1)

你需要的是什么:

static void Main(string[] args)
{
    string yafs = "Looking for LOVE in all the wrong love places...";
    string searchTerm = "LOVE";

    Console.Write(ReplaceInsensitive(yafs, searchTerm));
    Console.Read();
}

private static string ReplaceInsensitive(string yafs, string searchTerm)
{
    StringBuilder sb = new StringBuilder();
    foreach (string word in yafs.Split(' '))
   {
        string tempStr = word;
        if (word.ToUpper() == searchTerm.ToUpper())
        {
            tempStr = word.Insert(0, "<span style='background-color: #FFFF00'>");
            int len = tempStr.Length;
            tempStr = tempStr.Insert(len, "</span>");
        }

        sb.AppendFormat("{0} ", tempStr);
    }

    return sb.ToString();
}

给出:

  

寻找&lt; span style ='background-color:#FFFF00'&gt; LOVE&lt; /跨度&GT;在所有错误&lt; span style ='background-color:#FFFF00'&gt; love&lt; /跨度&GT;地方...

答案 1 :(得分:1)

怎么样:

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs, "(" + searchTerm + ")", "<span style='background-color: #FFFF00'>$1</span>", RegexOptions.IgnoreCase);
}

更新

public static string ReplaceInsensitive(string yafs, string searchTerm) {
    return Regex.Replace(yafs,
        "(" + Regex.Escape(searchTerm) + ")", 
        "<span style='background-color: #FFFF00'>$1</span>",
        RegexOptions.IgnoreCase);
}

答案 2 :(得分:0)

检查此代码

    private static string ReplaceInsensitive(string text, string oldtext,string newtext)
    {
        int indexof = text.IndexOf(oldtext,0,StringComparison.InvariantCultureIgnoreCase);
        while (indexof != -1)
        {
            text = text.Remove(indexof, oldtext.Length);
            text = text.Insert(indexof, newtext);


            indexof = text.IndexOf(oldtext, indexof + newtext.Length ,StringComparison.InvariantCultureIgnoreCase);
        }

        return text;
    }