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

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

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

$c = $c -replace [regex]::Escape('[email protected]#$%^&*(){}[]/:;,.?/"'),('-')

Write-Host $c

有直接的方式找到所有的特殊字符,空格和使用单个字符连字符替换

回答:

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

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

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

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

回答:

代码

$original = 'This_is my code [email protected]# 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"

结果

Original: This_is my code [email protected]# 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-----------_--------

以上是 Powershell用连字符替换空格和特殊字符 的全部内容, 来源链接: utcz.com/qa/261845.html

回到顶部