我试图只替换第一次出现的某些文本,首先是在http://regexpal.com/等在线工具中,然后看看这是否适用于 MSBUILD 任务。
我可以像这样在.net中做我想做的事:
StringBuilder sb = new StringBuilder();
sb.Append("IF @@TRANCOUNT>0 BEGIN");
sb.Append("IF @@TRANCOUNT>0 BEGIN");
sb.Append("IF @@TRANCOUNT>0 BEGIN");
Regex MyRgx = new Regex("IF @@TRANCOUNT>0 BEGIN");
string Myresult = MyRgx.Replace(sb.ToString(), "foo", 1);
如前所述,让这个在 MSBUILD 任务中工作是我的最终目标。我最接近的是替换除最后一个以外的所有内容(诚然,它没有关闭!)
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets" />
<ItemGroup>
<SourceFile Include="source.txt" />
<FileToUpdate Include="FileToUpdate.txt" />
</ItemGroup>
<Target Name="go">
<!-- a) Delete our target file so we can run multiple times-->
<Delete Files="@(FileToUpdate)" />
<!-- b) Copy the source to the version we will amend-->
<Copy SourceFiles= "@(SourceFile)"
DestinationFiles="@(FileToUpdate)"
ContinueOnError="false" />
<!-- c) Finally.. amend the file-->
<FileUpdate
Files="@(FileToUpdate)"
Regex="IF @@TRANCOUNT>0 BEGIN(.+?)"
ReplacementText="...I have replaced the first match only..."
Condition=""/>
<!-- NB The above example replaces ALL except the last one (!)-->
</Target>
</Project>
谢谢