amiros
November 7, 2020, 5:33am
1
Hi to all,
I am trying to find out away how to trim a string from a specific character.
let say I have a package name: Baybon_v1.0
How can I trim this to show only: Babylon
Another example:
Microsoft office professional_v2016
Would like to trim the text starting β_β
The result should be:
Microsoft office professional
Thank you so much for your time and help
Amir
Β
This example is hardcoded but it works
[string] $str1 = "Baybon_v1.0"
$str1.TrimEnd("_v1.0")
OUTPUT = Baybon
$str1 = "Microsoft office professional_v2016"
$str1.TrimEnd("_v2016")
OUTPUT = Microsoft office professional
Β
If you want this to be generic, such as function that works for all cases, consider wildcards or regexes in
combination with String.Trim()
<p style=βtext-align: left;β>Another option would be to use Split. You can split string by specific character and create array.</p>
On you case you will split by _ and will use the first element of that array.
$str1 = "Baybon_v1.0"
$str1.split('_')[0]
Hope that helps
Few more options
$text = 'Microsoft office professional_v2016'
$text -replace '_.+'
$text -split '_' | select -First 1
($text -split '_')[0]
If($text -match '.+(?=_)'){$matches.0}
amiros
November 8, 2020, 9:59am
5
WOW⦠i never thought there are so may ways to do one complex task
Thank you guys