从文本字符串中删除特定单词?

Removing specific words from a text string?

假设您有一个可变字符串,例如:"Report to Sam.Smith"

使用 Powershell 删除单词“Report”和“to”只留下 Sam.Smith 的最佳方法是什么?

你必须使用 -replace :

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

或者像这样:

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

但是如果你需要使用正则表达式,因为字符串的单词可能会有所不同,那么你必须重新考虑这个问题。

您不会希望擦除字符串的一部分,而是提取其中的某些内容。

在你的情况下,我认为你正在寻找使用 name.lastname 格式的用户名,这种格式很容易捕获:

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

使用 -匹配 将 return 真/假。

如果它 return 为真,将创建一个名为 $Matches 的数组。它将在索引 0 ($Matches[0]) 上包含与正则表达式匹配的整个字符串。

其他所有大于 0 的索引都将包含来自称为“捕获组”的正则表达式括号中的捕获文本。

我强烈建议使用 if 语句,因为如果您的正则表达式 return 为假,数组 $Matches 将不存在 :

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