Search code examples
regexpowershellscripting

Removing specific words from a text string?


So say you have a variable string like: "Report to Sam.Smith"

What's the best way for you to remove the words 'Report' and 'to' leaving only Sam.Smith using Powershell??


Solution

  • You have to use -replace :

    $string = "Report to Sam.Smith"
    $string = $string -replace "Report to ",""
    $string # Output --> "Sam.Smith"
    

    Or like this :

    $string = "Report to Sam.Smith"
    $string = $string.replace("Report to ","")
    $string # Output --> "Sam.Smith"
    

    But if you need to use Regex because the string's words can vary then you have to rethink the problem.

    You won't be looking to erase a part of the string but to extract something out of it.

    In you case, I think that you're looking for a username using a name.lastname format which is pretty easy to capture :

    $string = "Report to Sam.Smith"
    $string -match "\s(\w*\.\w*)"
    $Matches[1] # Output --> Sam.Smith
    

    Using -match will return True / False.

    If it does return True, an array named $Matches will be created. It will contains on index 0 ($Matches[0]) the whole string that matched the regex.

    Every others index greater than 0 will contains the captured text from the regex parenthesis called "capture group".

    I would highly recommend using an if statement because if your regex return false, the array $Matches won't exist :

    $string = "Report to Sam.Smith"
    if($string -match "\s(\w*\.\w*)") {
        $Matches[1] # Output --> Sam.Smith
    }