I want to build a PowerShell script which returns everything which occurs after the occurrence of the given string. I want to run a command against a single string instead of a collection.
E.g. I want to return everything after the phrase "_blah_"
_blah_v2.3
_blah_bar_blah_v56
_blah_v42
foo
Result:
v2.3
bar_blah_v56
v42
Probably Regex would be too heavy for such operation so looking for some alternative solution I've tried this:
$Foo = "blah_v1.1"
$FooVersion = ($Foo -split '_blah_', 2)[1]
Write-Host $Foo
Write-Host $FooVersion
but it works only with a single character instead of a string. I'm not fluent in PowerShell and looking for some quick and handy solution.
Probably Regex would be too heavy for such operation
No, it wouldn't.
"_blah_v2.3" -replace '^.*?_blah_'
So the string with the given phrase differs from your previous question, but for the rest there is not much difference.
Use something like
$FooVersion = $Foo -replace '_?blah_(.*)', '$1'
or
$FooVersion = ($Foo -split '_?blah_', 2)[-1]
or
if ($Foo -match '_?blah_(.*)') { $FooVersion = $Matches[1] } else { $FooVersion = $Foo }
would do it.
Please also read the explanation given by mklement0. That will surely help in future cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With