[英]Replacing Paths in a File with Regex in C#
因此,我有一个包含一些文件路径的文本文件。 这些路径需要部分替换。 这需要区分大小写,因此我尝试使用Regex进行此操作。
该文件的一部分如下所示:
PATH1 = d:\Software\system\SETUP\folder1
PATH2 = d:\Software\system\SETUP\folder2
PATH3 = d:\Software\system\SETUP
第一部分: d:\\Software\\system
需要替换为c:\\Software\\system
我用以下代码尝试了此操作:
string text = File.ReadAllText(filePath);
string pattern = "d:\\Software\\system";
string replace = "C:\\Software\\system";
string newText = Regex.Replace(text, pattern, replace, RegexOptions.IgnoreCase);
File.WriteAllText(filePath, newText);
但是,这不会更改文件中的任何内容。 我还使用断点来分析“替换”行之后的newText值,它与文件的写入没有任何关系。
任何帮助深表感谢!
使用Regex.Escape
方法将转义您的文字模式:
这是一个测试代码 :
var text = @"PATH1 = d:\Software\system\SETUP\folder1
PATH2 = d:\Software\system\SETUP\folder2
PATH3 = d:\Software\system\SETUP";
string pattern = "d:\\Software\\system";
string replace = "C:\\Software\\system";
string newText = Regex.Replace(text, Regex.Escape(pattern), replace.Replace("$", "$$"), RegexOptions.IgnoreCase);
// ^^^^^^^^^^^^^
Console.WriteLine(newText);
另一种方法是使用您需要与CompareMethod.Text
一起使用的Microsoft.VisualBasic.Strings.Replace
:
Text
可选的。 基于不区分大小写的文本排序顺序来进行字符串比较,该排序顺序由系统的语言环境决定 。
如果您的字符串包含所有文本字符,并且要在考虑到字母等价形式(例如不区分大小写和紧密相关的字母)的情况下进行比较,则这种类型的比较很有用。 例如,您可能需要考虑A和a相等,而Ä和ä优先于B和b。
码:
var newText = Microsoft.VisualBasic.Strings.Replace(text,
pattern,
replace,
Compare: Microsoft.VisualBasic.CompareMethod.Text);
在您的模式中,\\ S表示非空白,\\ s表示空白。 您需要通过使用自己的反斜杠转义来制作反斜杠文字:
所以:
string pattern = @"d:\\Software\\system";
要么:
string pattern = "d:\\\\Software\\\\system";
对于文件路径,您可以转换路径,模式并替换.ToUpper()
,然后执行普通string newPath = path.Replace(pattern, replace);
PS:如果生成的路径字符串大小写很重要,那么Regex.Escape
解决方案更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.