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-spaces-----------_--------'
$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-spaces-----------_--------
Result : This_is-my-code-----characters-are-not---allowed--remove-spaces-----------_--------
+0
'\ w'与'[a-zA-Z_]'相同'... – TheIncorrigible1
定义特殊。你想要什么角色?只是a-z,A-Z,0-9和连字符? –
所以输出应该是这样的 - 'This_is-my-code ----- characters-are-not --- allowed - remove-spaces -----------_---- ----' –
无论哪里有空间,我都想替换连字符。无论哪里有特殊的角色,我都想用空间替换。空间将再次被替换为连字符。 – user2598808