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

问题描述

假设您有一个变量字符串,例如:"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

使用 -match 将返回 True / False。

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

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

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

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