Am I able to get "bear" using one line using piping?
With strings already stored in memory, there is no good reason to use the pipeline - it will only slow things down.
Instead, use PowerShell's operators, which are faster than using a pipeline and generally more flexible than the similarly named .NET [string]
type's methods, because they operate on regexes (regular expressions) and can also operate on entire arrays:
PS> ('dog.puppy/cat.kitten/bear.cub' -split '[/.]')[-2]
bear
That is, split the input string by either literal /
or literal .
(using a character set, [...]
), and return the penultimate (second to last) ([-2]
) token.
See this answer for why you should generally prefer the -split
operator to the String.Split()
method, for instance.
The same applies analogously to preferring the -replace
operator to the String.Replace()
method.
It's easy to chain these operators:
PS> ('dog.puppy/cat.kitten/bearOneTwoThree.cub' -split '[/.]')[-2] -csplit '(?=\p{Lu})'
bear
One
Two
Three
That is, return the penultimate token and split it case-sensitively (using the -csplit
variation of the -split
operator) whenever an uppercase letter (\p{Lu}
) starts, using a positive look-ahead assertion, (?=...
).