-1

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??

TheGameiswar
  • 25,396
  • 5
  • 48
  • 82
Skeer
  • 157
  • 7
  • 2
    Please define "good" - what would make one appoach "better" than another? – Mathias R. Jessen Feb 19 '21 at 15:49
  • probably a `replace` – Abraham Zinala Feb 19 '21 at 15:54
  • 1
    or `("Report to Sam.Smith" -split '\s')[-1]` – Theo Feb 19 '21 at 16:00
  • It looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Feb 19 '21 at 16:08

1 Answers1

3

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
}
PowerCat
  • 316
  • 7
  • 1
    Exactly what I needed, thank you! I wanted to comment about how this question was closely related to another/others. I tried searching here on Stackoverflow.. found many examples of people removing text from a string with symbols like "I want remove everything before and including the = sign". Or "I need to remove every 3rd letter" but I found *nothing* like what I was asking. So whomever thinks my question was similar is wrong. Thanks powercat, I HUGELY appreciate the help – Skeer Feb 19 '21 at 17:44
  • 1
    You're welcome. – PowerCat Feb 19 '21 at 18:08