Powershell用连字符替换空格和特殊字符

时间:2017-12-18 08:49:58

标签: regex string powershell replace special-characters

我想用连字符替换字符串中的任何特殊字符和空格。 以下是我的代码:

$c = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$c = $c -replace [regex]::Escape('!@#$%^&*(){}[]/:;,.?/"'),('-')
Write-Host $c

有没有直接的方法来查找所有特殊字符,空格并替换为单个字符连字符

2 个答案:

答案 0 :(得分:2)

\ W将替换任何非单词字符。它不会取代a-z, A-Z, 0-9

$c = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$c -replace '\W','-'

This_is-my-code-----characters-are-not---allowed--remove-spaces-----------_--------

答案 1 :(得分:0)

代码

if(a == 0)

结果

$original = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$desired  = 'This_is-my-code-----characters-are-not---allowed--remove-sp‌​aces-----------_----‌​----'

$replacements = "[^a-zA-Z_]" # anything that's _not_ a-z or underscore
$result = $original -replace $replacements, '-'

Write-Host "Original: $c"
Write-Host "Desired : $d"
Write-Host "Result  : $r"