简体   繁体   中英

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.

You may use

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM