Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Find a substring in a string with PowerShell and trim

Writer Mia Lopez

I am trying to trim a string with PowerShell.

Let's say you have the following string:

Test test test test test test /abc test test test

I want to 'find' the '/a' in the string and ultimately get the "abc" by finding the next space.

Is that doable with PowerShell?

3 Answers

 $positionSlashA = "Test test test test test test /abc test test test".IndexOf("/a") $result1 = "Test test test test test test /abc test test test".Substring($positionSlashA) $positionfirstspace = $result1.IndexOf(" ") $result1.Substring(0, $positionfirstspace)

Let's say that your string is $testString. This code snipped will work. It will grab the characters that begin with /a until the next white space.

$testString = "Test test test test test test /abc test test test"
$matchString = $testString -match '/a\w*\s' | % {$Matches.Values -replace '/','' -replace'\s',''}
Write-Host $matchString

Or with one line and not writing output. I only wrote output in the previous example to show you the result.

$testString = "Test test test test test test /abc test test test" -match '/a\w*\s' | % {$Matches.Values -replace '/','' -replace'\s',''}
4

I would use a named capture group

> if ('Test test test test test test /abc test test test' -match '/(?<Token>[a-z]+)') { $Matches.Token }
abc

This approach allows you to extract exactly the token that follows the '/'. No need to trim '/', or trailing spaces.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.