Friday, November 9, 2012

String replace: case insensitive issue

I one of my product i build a file renaming system. User has many options to rename file. Among those we have some string replace cases.

At first we tried String.Replace Method (System) to replace texts. Below code snipped is given how things look, the code is simple and may seems different as it taken from different context.

public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = preview.NewFileName.Replace(SearchText, ReplaceText);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Now the client wanted the replacement as such so that the search string should be case insensitive. Trick is simple we have to use regex in place of normal string replace, but with Regex option set to ignore case. Below code segment is given to show how it is done.


public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = Regex.Replace(preview.NewFileName, SearchText, ReplaceText,RegexOptions.IgnoreCase);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText,RegexOptions.IgnoreCase);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Last trick, while searching for text for first index, there is option to state ignoring case we have to use it.


int iIndexOfBegin = strSource.IndexOf(strBegin,StringComparison.InvariantCultureIgnoreCase);

Until next time.

No comments:

Post a Comment