Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

case insenstive string replace that correctly works with ligatures like "ß" <=> "ss"

I have build a litte asp.net form that searches for something and displays the results. I want to highlight the search string within the search results. Example:

Query: "p"
Results: a<b>p</b>ple, banana, <b>p</b>lum

The code that I have goes like this:

public static string HighlightSubstring(string text, string substring)
{
 var index = text.IndexOf(substring, StringComparison.CurrentCultureIgnoreCase);
 if(index == -1) return HttpUtility.HtmlEncode(text);
 string p0, p1, p2;
 text.SplitAt(index, index + substring.Length, out p0, out p1, out p2);
 return HttpUtility.HtmlEncode(p0) + "<b>" + HttpUtility.HtmlEncode(p1) + "</b>" + HttpUtility.HtmlEncode(p2);
}

I mostly works but try it for example with HighlightSubstring("ß", "ss"). This crashes because in Germany "ß" and "ss" are considered to be equal by the IndexOf method, but they have different length!

Now that would be ok if there was a way to find out how long the match in "text" is. Remember that this length can be != substring.Length.

So how do I find out the length of the match that IndexOf produces in the presence of ligatures and exotic language characters (ligatures in this case)?

like image 344
usr Avatar asked May 14 '10 15:05

usr


1 Answers

This may not directly answer your question but perhaps will solve your actual problem.

Why not substitute instead?

using System.Text.RegularExpressions;

public static string HighlightString(string text, string substring)
{
    Regex r = new Regex(Regex.Escape(HttpUtility.HtmlEncode(substring)),
                        RegexOptions.IgnoreCase);
    return r.Replace(HttpUtility.HtmlEncode(text), @"<b>$&</b>");
}

But what of the culture? If you specify a Regex as case-insensitive, it is culture-sensitive by default according to http://msdn.microsoft.com/en-us/library/z0sbec17.aspx.

like image 117
Andrew Avatar answered Oct 13 '22 00:10

Andrew