0

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.

2
  • $_ -replace 'MyCatalog_AB_\d+\.xml', 'MyCatalog.xml'. \d+ matches one or more digits, and \. matches a literal dot. Commented Aug 16, 2019 at 18:24
  • @WiktorStribiżew Perfect! I knew it had to be something pretty simple. RegEx just isn't my thing. If you post as an answer, I'll mark it as such. Thanks! Commented Aug 16, 2019 at 18:28

1 Answer 1

1

You may use

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.