正则表达式替换文件中的空格 link

Regex to replace spaces in file link

我正在使用 C# 处理一些文本,我需要一个正则表达式来将文件 link 中的空格替换为 %20。所以给定这段文字:

/*
**  2 > 1
**  1 < 2 
**  <file:\\server\dir one\dirtwo\file name.txt>
**  <just because>
**  1 < 2
**  2 > 1
**  <file:\\server\dir one\dirtwo\file name.txt>
**  2 > 1
*/

结果将是:

/*
**  2 > 1
**  1 < 2 
**  <file:\\server\dir%20one\dirtwo\file%20name.txt>
**  <just because>
**  1 < 2
**  2 > 1
**  <file:\\server\dir%20one\dirtwo\file%20name.txt>
**  2 > 1
*/

到目前为止,我已经想出了这个模式 \x20(?=(?:(?!<file:).)*>),但它匹配文件 link.

之外的一些空格

理想情况下,我只想使用正则表达式来做到这一点。我正在修改的文本是在 Visual Studio 中打开的当前文档(我创建了一个 VS 扩展)。对于其他一些文本更改,我在 EnvDTE.TextDocument 中使用 ReplacePattern 方法。我没有太多编写扩展的经验,所以这似乎比我能想到的任何其他方法都简单得多(我确实看过使用编辑点)。

解决方案

使用 TextDocument.ReplacePattern 方法在正则表达式中使用 lookbehind 或 lookahead 似乎存在问题,这会导致引发异常。在 Regex.Replace 中使用相同的表达式会按预期工作。如果不是这个问题,那么 Wiktor Stribiżew 提供的解决方案将是完美的。

为了简单起见,我实现了以下功能:

bool patternReplaced;
do
{
   patternReplaced = activeDoc.ReplacePattern(@"(<file:\{3}.*)\s(\S+>)", @"%20", (int)vsFindOptions.vsFindOptionsRegularExpression);
} while (patternReplaced);

您可以使用 Regex.Replace 来匹配 <file:...> 子字符串并使用匹配计算器替换空格:

var res = Regex.Replace(str, @"<file:\{3}[^>]+>", m => m.Value.Replace(" ", "%20"));

IDEONE demo

请注意,如果要转义的不仅仅是空格,您可以考虑使用 Uri.EscapeUriString(m.Value)(使用另一个正则表达式,例如 @"(?<=<file:\{3}[^<>]*)[^<>\]+")。

另一种使用无限宽度后视的解决方案:

@"(?<=<file:\{3}[^<>]*)\s"

并替换为 %20

this regex demo