2010-12-28 3 views

답변

4

하나의 솔루션은 콜백 사용 :

s = Regex.Replace(s, @"^\s+|\s+$", match => match.Value.Replace(' ', '_')); 

또는 사용 lookaround를 (조금 난이도) :

s = Regex.Replace(s, @"(?<=^\s*)\s|\s(?=\s*$)", "_"); 
+0

'new String ('_ ', match.Length)'가 더 적합 할 수도 있습니다. 오 잘. – Kobi

+0

확실히. 수행중인 작업이 무엇인지 명확하게 알 수있을뿐만 아니라 공간 이외의 다른 공백 문자도 처리 할 수 ​​있습니다. – Brian

1

당신은 또한이 아닌 정규식 솔루션을 선택,하지만 난 할 수있다 꽤 확신 할 수 없다 :

StringBuilder sb = new StringBuilder(s); 
int length = sb.Length; 
for (int postion = 0; (postion < length) && (sb[postion] == ' '); postion++) 
    sb[postion] = '_'; 
for (int postion = length - 1; (postion > 0) && (sb[postion] == ' '); postion--) 
    sb[postion] = '_'; 
s = sb.ToString(); 
+0

정규 표현식 질문에 너무 많이 대답했다고 생각합니다.이 작업을 수행하는 더 좋은 방법이있을 것이라고 확신합니다.'P' – Kobi

관련 문제