Reputation: 257
I'm trying to trim to the right of a certain character in a text string.
Currently I am using
$string = "1500 pixels"
$string.Trim(" pixels")
This works fine and returns 1500
but if the last characters aren't " pixels"
then it will fail. How do I trim to the right of " "
?
Upvotes: 1
Views: 3116
Reputation: 438123
James C.'s helpful answer works well, but just to show an alternative using the -replace
operator:
> '1500 pixels' -replace ' .*' # short for: '1500 pixels' -replace ' .*', ''
1500
Regular expression ' .*'
matches the first space and everything that comes after (.*
), and, due to the absence of a replacement string, replaces what was matched with the empty string, i.e., effectively removes the match.
In case you only want to trim from the rightmost space, LotPings offers this variation:
> '1500 pixels and more' -replace ' [^ ]*$'
1500 pixels and
[^ ]*$
matches any sequence (*
) of chars. that aren't a space char. ([^ ]
) through the end of the string ($
).
Upvotes: 6
Reputation: 13227
The Split()
method can do this for you, it split a string into an array using a delimiter.
You split the string using space " "
as the delimiter, then use [0]
to return the first element of the array - which is 1500
in your example:
$string = "1500 pixels"
$string.Split(" ")[0]
And [1]
to return the second element (pixels
), if you also want to know this:
$string.Split(" ")[1]
Upvotes: 6