【问题标题】:Regex in powershell for getting assembly version numberPowershell中的正则表达式用于获取程序集版本号
【发布时间】:2021-09-21 15:03:22
【问题描述】:

我正在尝试创建一个脚本,该脚本将从解决方案中查找并返回程序集版本。它涵盖了一些测试场景,但我找不到正确的正则表达式来检查格式是否正确(1.0.0.0 可以,但是 1.0.o.0)并且包含 4 位数字?这是我的代码。

function Get-Version-From-SolutionInfo-File($path="$pwd\SolutionInfo.cs"){
$RegularExpression = [regex] 'AssemblyVersion\(\"(.*)\"\)'
$fileContent = Get-Content -Path $path
foreach($content in $fileContent)
{
    $match = [System.Text.RegularExpressions.Regex]::Match($content, $RegularExpression)
    if($match.Success) {
        $match.groups[1].value
    }
}

}

【问题讨论】:

  • 试试$RegularExpression = [regex] 'AssemblyVersion\("(\d(?:\.\d){3})"\)'
  • 请添加几行您的 $fileContent 集合,看看哪些内容适用于该特定数据。

标签: regex powershell assemblyversions


【解决方案1】:
  • 将您的贪婪捕获组(.*)更改为非贪婪(.*?),这样只有下一个"匹配。

    • 替代方法是使用([^"]*)
  • 要验证字符串是否包含有效的(2 到 4 组件)版本号,只需将其转换为 [version] (System.Version)。

应用于您的函数,通过-replace operator优化捕获组的提取:

function Get-VersionFromSolutionInfoFile ($path="$pwd\SolutionInfo.cs") {
  try {
    [version] $ver = 
      (Get-Content -Raw $path) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'
  } catch {
    throw
  }
  return $ver
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多