문제

I'm trying to replace only the FIRST occurrence of some text, firstly from within an online tool such as http://regexpal.com/ and then see if this works in an MSBUILD task.

I can do what I want in .net like so:

        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);

As mentioned to get this working in an MSBUILD task is my ultimate aim. The closest I have come is to replace all except the last one (which admittedly ISN'T close!)

<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>

Thanks

도움이 되었습니까?

해결책

(.+?) in regex means that there will be additional text after BEGIN word, but looks like your test file just ends with this BEGINS - so it cannot match it.

Try using * instead of +, or add some garbage to the end of file - depends on your real needs.

To solve your initial task - use for example Singleline mode, which greedy match the rest of file:

<FileUpdate 
    Files="@(FileToUpdate)"
    Regex="(IF @@TRANCOUNT>0 BEGIN)(.*)" 
    ReplacementText="...I have replaced the first match only...$2"
    Singleline="true"
    Condition=""/>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top