2013-04-02 38 views
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> 

感謝

回答

3

在正則表達式(.+?)意味着,經過BEGIN話會有額外的文本,但長相就像你的測試文件以這個BEGINS結尾 - 所以它不能匹配它。

嘗試使用*而不是+,或在文件末尾添加一些垃圾 - 取決於您的實際需求。

爲了解決您最初的任務 - 例如使用單線模式,貪婪的匹配文件的其餘部分:

<FileUpdate 
    Files="@(FileToUpdate)" 
    Regex="(IF @@TRANCOUNT>0 BEGIN)(.*)" 
    ReplacementText="...I have replaced the first match only...$2" 
    Singleline="true" 
    Condition=""/> 
+0

我正要說的時候我在$ 2中添加的替換文本沒有奏效,嘿presto!這2美元的做法是什麼讓它起作用? –

+0

$ 1,$ 2等是通過正則表達式捕獲的,所以$ 2在這裏是'(。*)' - 「我的IF @@ TRANCOUNT> 0 BEGIN'」 – Lanorkin

+0

非常感謝:) [消失瞭解讀取。 ..] –

相關問題