Powershell / regex wildcard replace

I am trying to write a PowerShell script to update my .nuspec (nuget depdency) file to the latest build version. I'm having problems with wildcards.

So I want to replace the version number of this line

 <dependency id="MyCompany.Common" version="1.0.0.0" /> 

to the new version number, i.e. version 2.2.2.2

 <dependency id="MyCompany.Common" version="2.2.2.2" /> 

My current place method looks like this. Note. I need to have a wildcard, as I have several nuget packages in the solution I need to replace, all follow the format MyCompany.PackageName

 $filecontent -replace 'id="MyCompany.*" version="*"', "$Version" | Out-File $file 

But it actually ends up creating

 <dependency 2.2.2.21.0.0.0" /> 

How to change my regex so that it only replaces the version number?

+5
source share
3 answers

Replace

 $filecontent -replace 'id="MyCompany(.*?)" version=".*?"', "id=`"MyCompany`$1`" version=`"$Version`"" | Out-File $file 
+4
source

I went with the simple use of a capture group, so I do not lose the specification of your regular expression, matches only strings with "MyCompany. *" In id, but does not add a lot of complexity. I commit everything to the initial quote in the version and replace everything that is before the next quote with the new version number.

 $test='<dependency id="MyCompany.Common" version="1.0.0.0" />' $newVersion='2.2.2.2' $test -replace "(id=`"MyCompany`..*`" version=)`"[^`"]*","`$1`"$newVersion" <dependency id="MyCompany.Common" version="2.2.2.2" /> 

Tested in PS 4.0

The bizarre and fragile bits of Powershell include:

  • backtick to exit instead of \

  • regex must be in double quotes

  • must use single quotes or screens so that capture groups work in a replacement string

+2
source
 $s = '<dependency id="MyCompany.Common" version="2.2.2.2" />' $s -replace 'version=".*"', 'version="1.2.3.4"'<dependency id="MyCompany.Common" version="1.2.3.4" /> 
+1
source

Source: https://habr.com/ru/post/1264690/


All Articles