2

我正在尝试创建一个脚本,该脚本将从解决方案中找到并返回程序集版本。它涵盖了一些测试场景,但我找不到正确的正则表达式来检查版本的格式是否正确(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
    }
}

}

4

1 回答 1

1
  • 将您的贪婪捕获组 ,(.*)更改为非贪婪捕获组,(.*?)以便只有下一个"匹配。

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

应用于您的功能,通过-replace运算符优化捕获组的提取:

function Get-VersionFromSolutionInfoFile ($path="$pwd\SolutionInfo.cs") {
  try {
    [version] $ver = 
      (Get-Content -Raw $path) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'
  } catch {
    throw
  }
  return $ver
}
于 2021-07-12T13:37:34.100 回答