首页 > 解决方案 > 从文本字符串中删除特定单词?

问题描述

所以说你有一个变量字符串,如:"Report to Sam.Smith"

什么是你删除单词' Report'和' to'只Sam.Smith使用Powershell的最佳方法?

标签: regexpowershellscripting

解决方案


您必须使用-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
}

推荐阅读