2017-12-18 19 views
-2

문자열의 특수 문자와 공백을 하이픈으로 대체하려고합니다.Powershell은 공백과 특수 문자를 하이픈으로 바꿉니다.

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

+1

는 특별하다. 어떤 캐릭터가 좋을까요? 그냥 -Z, A-Z, 0-9 및 하이픈? –

+0

그래서 출력이 이렇게되어야합니다 - 'This_is-my-code ----- characters-are-not --- allowed - remove-spaces -----------_---- ---- ' –

+0

공간이 있으면 하이픈으로 바꾸고 싶습니다. 특수 문자가있는 곳이면 어디든 공백으로 바꾸고 싶습니다. 우주는 다시 하이픈으로 바뀔 것입니다. – user2598808

답변

1

\ 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-----------_-------- 
0

코드

$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-----------_-------- 
를 모든 특수 문자, 공백을 찾아 하나의 문자 하이픈으로 대체하는 직접적인 방법이 있나요 : 다음은 내 코드입니다
+0

'\ w'는'[a-zA-Z_]'와 같습니다 ... – TheIncorrigible1