如何删除重复字符

如何删除重复字符

我正在删除所有带连字符的特殊字符,效果很好,但在某些情况下会留下两个甚至三个连字符。我正在寻找一种方法来删除使用两个或更多连字符的情况。

$c = 'Aged Cheddar , White Wine, and Sweet Fig Cheese Spread Pinot Grigio & Fig'

$c = $c -replace '\W','-' 

输出:Aged-Cheddar---White-Wine--and-Sweet-Fig-Cheese-Spread-Pinot-Grigio---Fig

答案1

在第一次替换后添加以下内容:

$c = $c -replace '(-){2,}','-'

你的代码将会像这样:

$c = 'Aged Cheddar , White Wine, and Sweet Fig Cheese Spread Pinot Grigio & Fig'
$c = $c -replace '\W','-' 
$c = $c -replace '(-){2,}','-'

输出将是:

Aged-Cheddar-White-Wine-and-Sweet-Fig-Cheese-Spread-Pinot-Grigio-Fig

答案2

实现此目的的一种方法是让替换运行两次。第一次替换特殊字符,第二次用一个连字符替换两个或多个连字符。以下代码可以做到这一点,但可能不是最可靠的方法:

$c = ($c -replace '\W','-') -replace '--*','-'

输出:

Aged-Cheddar-White-Wine-and-Sweet-Fig-Cheese-Spread-Pinot-Grigio-Fig

注意:如果要将其包含在我编写的代码中,我会将其分为两个步骤以提高可读性,但这是个人喜好。例如:

$temp = $c -replace '\W','-' 
$c = $temp -replace '--*','-'

这里有一个好文章在 PowerShell 中使用 replace。

答案3

只需一次替换即可完成:

$c = 'Aged Cheddar , White Wine, and Sweet Fig Cheese Spread Pinot Grigio & Fig'
$c -replace '\W+','-'

输出:

PS C:\> $c = 'Aged Cheddar , White Wine, and Sweet Fig Cheese Spread Pinot Grigio & Fig'
PS C:\> $c -replace '\W+','-'
Aged-Cheddar-White-Wine-and-Sweet-Fig-Cheese-Spread-Pinot-Grigio-Fig
PS C:\>  

相关内容