Search code examples
regexpowershellrename

How to remove whitespace between numbers only?


I have a bunch of directories named differently like this:

firstname lastname (123) 456 7890
firstname lastname (234) 567-8910
firstname lastname 345-678-9101

I'm trying to rename each directory to keep the name with a space but have no spaces between the numbers like this:

firstname lastname 1234567890
firstname lastname 2345678910
firstname lastname 3456789101

This is what I have going right now:

$destination = "D:\test"

Get-ChildItem -Path $destination -Recurse -Directory |
Rename-Item -NewName { $_.name -replace '[()\s-]',''} -Verbose

##output##
firstnamelastname1234567890
firstnamelastname2345678910
firstnamelastname3456789101

This kind of works but doesn't leave a space between the firstname lastname and phone number. I've been trying other regex patterns but can't find a solution to target numbers. Is there a way to target the whitespace between only numbers?


Solution

  • You can use

    $_.name -replace '[^\w\s]*(\d+)\W*(?=[\d\W]*$)', '$1'
    

    See the regex demo

    Details

    • [^\w\s]* - any zero or more chars other than word and whitespace chars
    • (\d+) - Capturing group 1 ($1 refers to this value from the replacement pattern): one or more digits
    • \W* - any zero or more non-word chars...
    • (?=[\d\W]*$) - that are immediately followed with zero or more non-word or digit chars up to the end of string.