2013-04-07 77 views
3

我正在寻找清理包含文件路径的字符串,以删除用于更安全日志记录的父路径。.Net正则表达式替换 - 多行搜索文件路径

它需要:

  • 不区分大小写。
  • 支持无限制捕捉替换。在.NET
  • 工作接受被提供或替换是自动化的(我创建动态搜索模式)的路径,并且因此发生需要以自动化的方式进行复制的任何字符串福

我想采取一个多行字符串,如:

The file was: C:\\outputpath\\testfile.htm 
And the second file was: C:\\OutputPath\\subfolder\\testfile2.htm' 

,并将它查找和替换输出:

The file was: testfile.htm 
The second file was: subfolder\\testfile2.htm 

我一直在试图用这样的:

var pathToRemove = "c:\\outputPath"; 
var sourceRegex = new Regex(".*(" + pathToRemove + ").*", RegexOptions.IgnoreCase); 
var sanity = sourceRegex.Replace(input, String.Empty, 1000); 

我发现了一个异常

Unrecognized escape sequence \o.

+0

你只关心替换字符串'C:\\ output',或者你想删除任何对本地文件路径的引用? – 2013-04-07 05:23:13

+0

只是提到的文件路径。 – Doug 2013-04-07 05:24:37

+0

如果添加“@”,如@“c:\\ outputPath”,则异常将消失。 – 2013-04-07 05:42:08

回答

3
string pathToRemove = @"c:\\outputpath\\"; 
Regex sourceRegex = new Regex(pathToRemove, RegexOptions.IgnoreCase); 
string sanity = sourceRegex.Replace(input, string.Empty); 
+0

我不能相信这是这么简单... – Doug 2013-04-07 06:09:32

+0

这总是简单的事情,让我也是。 – PLED 2013-04-07 06:14:31