2014-12-10 3 views
0

정규 표현식과 일치하는 문자열 부분 만 바꾸려면 도움이 필요합니다. 예를 들어, 나는 다음과 같은 텍스트가 : 나는이 단어 앞에와 말씀으로 진행되도록 새로운 라인 문자를 찾을 필요가정규 표현식 일치 부분 바꾸기

This is some sentence 
and the continuation of the sentence 

을, 그래서 나는 다음과 같은 정규식 사용

Regex rgx = new Regex("\w\n\w"); 

이 조건을 찾으면 줄 바꿈 문자 만 공백으로 바꾸기를 원합니다. 출력은 다음과 같습니다.

This is some sentence and the continuation of the sentence 

이렇게 할 수 있습니까?

UPDATE 12/11/14이 :

이 질문은 중복으로 표시되었다, 그러나, 참조 된 솔루션은 내가 찾던 정확히 무엇을이었다. 위에서 언급했듯이 새로운 줄이 문자로 시작되고 진행되는 시나리오 여야합니다. 참조 된 솔루션은 모든 '\ n'문자를 잡아서 빈 문자열로 바꿉니다.

string input = "This is some sentence\nand the continuation of the sentence", 
     pattern = @"(\w)\n(\w)", 
     replacement = "$1 $2", 
     output = string.Empty; 

output = Regex.Replace(input, pattern, replacement); 

이의 결과는 다음과 같습니다 :

This is some sentence and the continuation of the sentence 

내 솔루션은 this solution에서 영감을받은 다음

내 문제에 대한 해결책이었다.

+0

그것은 단지 개행 일 수 없습니다. 실제 텍스트 문자로 바로 시작되고 진행되는 개행이어야합니다. – Anthony

답변

0

문자열을 위로 나눠서 새 조인트와 함께 다시 설정하십시오. 당신은 다음과 같이 할 수 있습니다 :

string input = "This is a sentence\nand the continuation of the sentence.\n\nLet's go for\na second time."; 

var rx = new Regex(@"\w(\n)\w"); 

var output = new StringBuilder(); 

int marker = 0; 

var allMatches = rx.Matches(input); 
foreach (var match in allMatches.Cast<Match>()) 
{ 
    output.Append(input.Substring(marker, match.Groups[1].Index - marker)); 
    output.Append(" "); 
    marker = match.Groups[1].Index + match.Groups[1].Length; 
} 
output.Append(input.Substring(marker, input.Length - marker)); 

Console.WriteLine(output.ToString());