Search code examples
c#regex.net-coremsbuildcsproj

Regex that is working in C# is not working in MSBuild


I want to verify that the version being used when packing some nuget-packages using dotnet build /p:VERSION=1.2.3 and GeneratePackageOnBuild. My regex expressen is working in LINQPad 6 using C#:

Regex.Match("1.2.3", @"^\d{1,3}\.\d{1,3}\.\d{1,6}(-(beta|rc)(\d{1,1})?)?$")

However in my default.props that is being imported by all csproj-files (which are using the new sdk-style, if that is relevant) I have this and it is not working at all:

<Target Name="ValidateVersion" BeforeTargets="BeforeBuild">
  <PropertyGroup>
    <VersionRegex>^\d{1,3}\.\d{1,3}\.\d{1,6}(-(beta|rc)(\d{1,1})?)?$</VersionRegex>
    <VersionTest>1.2.3</VersionTest> <!-- Just to make it easier during testing -->
  </PropertyGroup>

  <Error
    Text="Version is not following the correct format: $(VersionRegex)"
    Condition=" $([System.Text.RegularExpressions.Regex]::IsMatch('$(VersionTest)', `$(VersionRegex)`)) " />
</Target>

It does not matter if I inline VersionRegex and VersionTest, it is still not working. Any ideas why it is working in C# but not in MSBuild?


Solution

  • From your original example, you should be able to put the content of the VersionRegex property within CDATA:

    <Target Name="ValidateVersion" BeforeTargets="BeforeBuild">
      <PropertyGroup>
        <VersionRegex><![CDATA[^\d{1,3}\.\d{1,3}\.\d{1,6}(-(beta|rc)(\d{1,1})?)?$]]></VersionRegex>
        <VersionTest>1.2.3</VersionTest>
      </PropertyGroup>
    
      <Error
        Text="Version is not following the correct format: $(VersionRegex)"
        Condition="!$([System.Text.RegularExpressions.Regex]::IsMatch('$(VersionTest)', '$(VersionRegex)'))" />
    </Target>