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


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

Comments (1)

  1. hpotsirhc says:

    This is really nice. I never mentioned using lookahead without a sign before, like ".(?=\.)"

Skip to main content