Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a filter for string which contains given phrase and return everything which occurs after

Tags:

powershell

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.

like image 414
GoldenAge Avatar asked Dec 19 '18 14:12

GoldenAge


2 Answers

Probably Regex would be too heavy for such operation

No, it wouldn't.

"_blah_v2.3" -replace '^.*?_blah_'
like image 162
Tomalak Avatar answered Nov 17 '22 16:11

Tomalak


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.

like image 1
Theo Avatar answered Nov 17 '22 15:11

Theo