c# - 在 C# 中工作的正则表达式在 MSBuild 中不起作用

标签 c# regex .net-core msbuild csproj

我想验证使用 dotnet build/p:VERSION=1.2.3GeneratePackageOnBuild 打包某些 nuget 包时所使用的版本。我的正则表达式正在使用 C# 在 LINQPad 6 中工作:

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

但是,在我的由所有 csproj 文件(正在使用新的 sdk 样式,如果相关的话)导入的 default.props 中,我有这个,但它根本不起作用:

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

如果我内联 VersionRegexVersionTest 也没关系,它仍然无法工作。知道为什么它可以在 C# 中工作但不能在 MSBuild 中工作吗?

最佳答案

根据您的原始示例,您应该能够将 VersionRegex 属性的内容放入 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>

关于c# - 在 C# 中工作的正则表达式在 MSBuild 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59095328/

相关文章:

c# - UWP 中的 Xamarin Forms MasterDetailPage 按钮填充问题

c# - Windows 7 Home Premium 是否允许 (File.Encrypt)?

c++ - C++ 中的正则表达式跳过

regex - 如何在 Java 中使用正则表达式从定界字符串中仅提取特定类型的值

c# - linq-to-sql 是否处理动态查询?

javascript - ExtJS:验证整小时时间

dependency-injection - 如何构建 IOptionsMonitor<T> 进行测试?

c# - 引用 Razor 类库时重复的基本路径

c# - Log4Net 记录到特定 Appender .NET Core

c# - HTML 标签替换多行