Scott Marcus
Scott Marcus

Reputation: 65806

Replace Wildcard Value in String with PowerShell

I am trying to simply remove a known string and an unknown number in a string from a string using the Powershell replace command and can't quite figure the syntax for a wildcard out.

My input string looks like this:

MyCatalog_AB_24.xml

However, the number is dynamic and won't always be 24.

And I need to wind up with:

MyCatalog.xml

So, I need to remove anything between MyCatalog and .xml (essentially the _AB_## part).

Here's the commands I've tried:

$_ -replace 'MyCatalog_AB_*.xml', 'MyCatalog.xml'
$_ -replace 'MyCatalog*.xml', 'MyCatalog.xml'

set num='\d'
$_ -replace 'MyCatalog_AB_%num%.xml', 'MyCatalog.xml'

I know I should be using some sort of regular expression, but I have some working code that someone else wrote that does something similar by just inserting an * where the wildcard data is.

Any help would be appreciated.

Upvotes: 0

Views: 279

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use

$_ -replace 'MyCatalog_AB_\d+\.xml', 'MyCatalog.xml'. 

\d+ matches one or more digits, and \. matches a literal dot.

Upvotes: 1

Related Questions