使用 regex + powershell 替换匹配组

replace match group using regex + powershell

我正在尝试设置一个 PowerShell 脚本来替换我的 GlobalAssemblyInfo.cs 文件中的匹配字符串。我基本上是想通过 powershell 更新版本号,这样我就可以在 post 构建中自动更新。无论如何,cs 文件的输入字符串是这样的:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Runtime.InteropServices;


[assembly: System.Reflection.AssemblyVersion("1.1.31.0")]
[assembly: System.Reflection.AssemblyCompany("Name")]
[assembly: System.Reflection.AssemblyProduct("Name")]
[assembly: System.Reflection.AssemblyCopyright("Name")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

我正在尝试的 PowerShell 脚本是这样的:

$file = "C:\users\konrad\desktop\GlobalAssemblyInfo.cs"
$pattern = '^\[assembly: System\.Reflection\.AssemblyVersion\("(.*)"\)\]'
$version = '2.0.0.0_delta'

(Get-Content $file).replace($pattern, " $version") | Set-Content $file

同样,我们的想法是获取 ("") 之间的版本号,并将其替换为名为 $version 的字符串。上面的代码我没有收到任何错误。它根本行不通。任何想法将不胜感激。

干杯!

编辑:

@Abraham Zinala 建议改用 -replace。我试过了。

(Get-Content $file) -replace $pattern, "$version" | Set-Content $file

这取代了这个:

[assembly: System.Reflection.AssemblyVersion("1.1.31.0")]

进入这个:

2.0.0.0_delta

我要的是这个:

[assembly: System.Reflection.AssemblyVersion("2.0.0.0_delta")]

already pointed out the key issue, .Replace(..) string method is not regex compatible, you can use the -replace operator 用于正则表达式替换。至于您想要的输出,您可以使用以下模式:

$pattern = '(?m)(^\[assembly: System\.Reflection\.AssemblyVersion\(")[\d.]+'
$version = '2.0.0.0_delta'

(Get-Content $file -Raw) -replace $pattern, "`$version" | Set-Content ...

请参阅 https://regex101.com/r/VLoUN2/1 了解说明。

您可能希望将 [\d.]+ 更改为 [\w\d.]+ 以防您要查找的版本替换还可以包含 个单词字符和下划线 .