Reputation: 154
I am writing a function in powershell, and part of it needs to replace occurrences of substrings with a wildcard. Strings will look something like this:
"something-#{reference}-somethingElse-#{anotherReference}-01"
I want it to end up looking like this:
"something-*-somethingElse-*-01"
The problem I have here is that I don't know what "#{something}" will be, just that there will be multiple substrings enclosed inside a hashtag followed by curly braces. I've tried the Replace method like so:
$newString = $originalString.Replace('#{*}', '*')
I was hoping that would replace everything from the hashtag to the ending curly brace, but it doesn't work like that. I'm trying to avoid cumbersome code that is based on finding the indices of '#' and '}' and then replacing, and hoping there is a simpler and more elegant solution.
Upvotes: 0
Views: 928
Reputation: 28963
Your replace has at least one problem, possibly two;
the method $string.Replace()
is from the .Net framework string class - it's PowerShell, but it's exactly what you'd get in C#, minimal PowerShell script-y convenience added on top - and it's for literal text replacements - it doesn't support wildcards or regular expressions.
The 'wildcard' support in PowerShell is quite limited, to the -like
operator only, as far as I know. That can't do text replacing, and it's a convenience for people who don't know regular expression; behind the scenes it converts to a regular expression anyway. So the dream of a a*b
replace won't work either.
As @PetSerAl comments, regular expressions and the PowerShell -replace
operator are the PowerShell way to do every string pattern replace quickly and without .indexOf()
.
Their pattern #{[^}]*}
expands to:
#{}
on the outside, as literal characters
[^}]
as a character class saying "not a }
character, but anything else"[*}]*
- as many not }'s
as there are.So, match hash and open brace, everything that isn't the closing brace brace (to avoid overrunning past the closing brace), then the closing brace. Replace it all with literal *
.
Implicitly, do that search/replace as many times as possible in the input string.
Upvotes: 3