我想用连字符替换字符串中的任何特殊字符和空格。 以下是我的代码:
$c = 'This_is my code !@# characters are not $ allowed% remove spaces ^&*(){}[]/_:;,.?/"'''
$c = $c -replace [regex]::Escape('!@#$%^&*(){}[]/:;,.?/"'),('-')
Write-Host $c
有没有直接的方法来查找所有特殊字符,空格并替换为单个字符连字符
答案 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-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"