0
我試圖只替換一些文本的第一次出現,首先從http://regexpal.com/等在線工具中取出,然後查看這是否適用於MSBUILD任務。RegEX - 僅替換第一次出現的文本
我可以做我想做的.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>
感謝
我正要說的時候我在$ 2中添加的替換文本沒有奏效,嘿presto!這2美元的做法是什麼讓它起作用? –
$ 1,$ 2等是通過正則表達式捕獲的,所以$ 2在這裏是'(。*)' - 「我的IF @@ TRANCOUNT> 0 BEGIN'」 – Lanorkin
非常感謝:) [消失瞭解讀取。 ..] –