简体   繁体   中英

String.Replace method ignores case with special characters.

I have a string containing a server file path ($\\MyPath\\Quotas\\ExactPath\\MyFile.txt) and a local file system path (C:\\MyLocalPath\\Quotas\\ExactPath). I want to replace the server file path with the local system path.

I currently have an exact replace:

String fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
String sPath = @"$\MyPath\Quotas\ExactPath\";
String lPath = @"C:\MyLocalPath\Quotas\ExactPath\";

String newPath = fPath.Replace(sPath, lPath);

But I want this to be a case-insensitive replace, so that it would replace $\\MyPath\\quotas\\Exactpath\\ with lPath as well.

I came across the use of Regular Expressions like the following:

var regex = new Regex( sPath, RegexOptions.IgnoreCase );
var newFPath = regex.Replace( fPath, lPath );

But how do I handle the special characters ($,\\,/,:) so that it is not interpreted as a regular expression special character?

You can use Regex.Escape :

var regex = new Regex(Regex.Escape(sPath), RegexOptions.IgnoreCase);
var newFPath = regex.Replace(fPath, lPath);

Just use Regex.Escape :

fPath = Regex.Escape(fPath);

This escapes all metacharacters and turns them into literals.

As you are only after the case sensetivity setting, and not any regular expression matching, you should rather use String.Replace rather than Regex.Replace . Surprisingly enough there is no overload of the Replace method that takes any culture or comparison settings, but that can be fixed with an extension method:

public static class StringExtensions {

  public static string Replace(this string str, string match, string replacement, StringComparison comparison) {
    int index = 0, newIndex;
    StringBuilder result = new StringBuilder();
    while ((newIndex = str.IndexOf(match, index, comparison)) != -1) {
      result.Append(str.Substring(index, newIndex - index)).Append(replacement);
      index = newIndex + match.Length;
    }
    return index > 0 ? result.Append(str.Substring(index)).ToString() : str;
  }

}

Usage:

String newPath = fPath.Replace(sPath, lPath, StringComparison.OrdinalIgnoreCase);

Testing the performance, this shows to be 10-15 times faster than using Regex.Replace .

I would recommend not using Replace at all. Use the Path class in System.IO:

string fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
string lPath = @"C:\MyLocalPath\Quotas\ExactPath\";

string newPath = Path.Combine(lPath, Path.GetFileName(fPath));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM