删除代码段

时间:2011-03-21 11:24:14

标签: regex

我有一个像这样的代码块:

<Compile Include="Share\System\Master\Relative\RelativeList.aspx.designer.cs">
  <DependentUpon>RelativeList.aspx</DependentUpon>
</Compile>
<Compile Include="Share\System\Master\Status\StatusInfo.aspx.cs">
  <DependentUpon>StatusInfo.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="Share\System\Master\Status\StatusInfo.aspx.designer.cs">
  <DependentUpon>StatusInfo.aspx</DependentUpon>
</Compile>
<Compile Include="Share\System\Master\Status\StatusList.aspx.cs">
  <DependentUpon>StatusList.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>

我想删除所有与以下内容类似的块代码:

<Compile Include="Share\System\Master\Relative\RelativeList.aspx.designer.cs">
  <DependentUpon>RelativeList.aspx</DependentUpon>
</Compile>

我的意思是它以<Compile开头,包含.aspx.designer.cs,以</Compile>结尾

所以,当我删除所有类似的代码时,剩下的就是这样:

<Compile Include="Share\System\Master\Status\StatusInfo.aspx.cs">
  <DependentUpon>StatusInfo.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>
<Compile Include="Share\System\Master\Status\StatusList.aspx.cs">
  <DependentUpon>StatusList.aspx</DependentUpon>
  <SubType>ASPXCodeBehind</SubType>
</Compile>

因为我将网站转换为Web应用程序所以我必须删除所有的design.cs页面并重新创建它们,以便不会发生错误重复的控件。

问题是我有很多页面:((

提前致谢:)

更新:我在Visual Studio中使用快速查找和替换

1 个答案:

答案 0 :(得分:0)

您需要将正则表达式匹配器切换为单行模式。

Regex.Replace(
    input,
    @"<Compile Include=""[^""]*""(?<=aspx.designer.cs"").*?</Compile>",
    "",
    RegexOptions.Singleline);

通常,正则表达式不是解析XML的好选择。最好只加载XML文档并过滤/删除所需的节点。

但是,在这个例子中,Regex可以做你想要的,因为文档的结构相对简单。它首先查找Compile open标记,然后在Include中找到文件名。它将匹配文件名,直到找到双引号。然后它会返回并确保匹配的最后一个字符为aspx.designer.cs"。然后它将懒惰地查找关闭的Compile标记,以防止它吞噬文件的其余部分。

编辑:我认为您无法在Visual Studio查找/替换对话框中执行此操作。据我所知,你无法将其切换到单行模式。每当我尝试提供(?s)时,它就会开始只是不匹配任何东西。因此,无法从打开的Compile标记捕获到关闭的Compile标记。似乎看起来也不会起作用。

为什么不使用PowerShell?您可以将上述内容提供给PowerShell。

[Regex]::Replace( $(cat .\XMLFile1.xml), '<Compile Include="[^"]*"(?<=aspx\.designer\.cs").*?</Compile>', "", "Singleline");