regexpowershell

How To Use Regex in Powershell to replace all but first character of a match


I am using PowerShell to perform a series of replace functions against a variable, therefore am trying to keep it that way rather than write more lines of code to manipulate.

I have a regex with finds an expression that begins and ends with a wildcard and looks for a specific text with the string. Once it finds a match, I want it to take what it found and just give me the first character and allow me to add one more character to it. I have tried the $0 value but this seems to be the whole match and not part of the match

I am using -replace '^(.*INS).*?.*' and so if the text has "INS" in it I want the text replace to whatever the very first character in the match found is with an added character, for example "V!".

Is this possible or at least be able to convert it to the first character in the match and turn the rest into repeating characters as I can piggy-back other replaces off this.


Solution

  • use $1 for the first match

    however you dont want INS inside it but the first characer

    hence (.) followed by more characters .* and the your INS

    "binsISTable" -replace '^(.).*INS.*', '$1!'
    

    i added the exclamation mark in the output after that