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

Regex Powershell使用连字符替换空格和特殊字符,regex,string,powershell,replace,special-characters,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 有没有直接的方法来查找所有特殊字符、空格并替换为单字符连字符代码 结果 \

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

$c = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$c = $c -replace [regex]::Escape('!@#$%^&*(){}[]/:;,.?/"'),('-')
Write-Host $c
有没有直接的方法来查找所有特殊字符、空格并替换为单字符连字符代码 结果
\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-----------_--------

定义特殊的。你想要什么角色?只有a-z,a-z,0-9和连字符?所以输出应该是这样的-'这是我的代码-----不允许字符-----删除空格-----如果有空格,我想用连字符替换。只要有一个特殊的字符,我想用空格代替。空格将再次被连字符取代。什么是特殊字符?é? ö? ®? “特殊角色”是一个非常宽泛和灵活的术语。定义什么是特殊字符可能更容易
Original: This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'
Desired : This_is-my-code-----characters-are-not---allowed--remove-sp‌​aces-----------_----‌​----
Result  : This_is-my-code-----characters-are-not---allowed--remove-spaces-----------_--------
$c = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$c -replace '\W','-'

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