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

Viewed 121

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.

3 Answers

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.

Unless performance is critical (extremely rare), regex is nice. I would use positive lookbehind. See following example:

$test = '_blah_v2.3 ','_blah_bar_blah_v56','blah_v42 ','foo'
($test | Select-String '(?<=blah_).*').Matches.Value

Note that I used blah_ as separator.

Related