October 21st, 2016

PowerTip: How to use regular expressions to split a string without losing the character you split on

Doctor Scripto
Scripter

Summary: Cloud and Datacenter Management MVP, Thomas Rayner, shows how to split a string without losing the character you split on.

Hey, Scripting Guy! Question I’m splitting this file name some file.txt into its name and extension by going “some file.txt” –split “.”. It’s giving me some file and txt, but I want to keep the dot and get .txt instead. How can I do this?

Hey, Scripting Guy! Answer You can split on a regex lookahead and split on the space between characters where the character on the right is a dot

'some file.txt' -split '(?=\.)'

The Doctor

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.