2010-08-13 2 views
3

Perl에서 한 줄의 큰 긴 문자열에서 줄 바꿈없이 텍스트 단락을 사용하여 어떻게 분할 및 RegEx (또는 다른 것)을 사용할 수 있습니까? monospaced 글꼴로 표시하기 위해 단락을 단어 경계에서 같은 크기의 청크로 분할하려면? 이에연속 단락을 포함하는 문자열을 왼쪽 정렬 열의 열로 분할

"When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community." 

: :이 변경 어떻게 예를 들어

,

"When you have decided which answer is the most \n" 
"helpful to you, mark it as the accepted answer \n" 
"by clicking on the check box outline to the \n" 
"left of the answer. This lets other people \n" 
"know that you have received a good answer to \n" 
"your question. Doing this is helpful because \n" 
"it shows other people that you're getting \n" 
"value from the community.\n" 

감사합니다, 벤

답변

4

물론 Text::Wrap을 사용하십시오. 하지만, 여기에 단지 그것의 지옥에 대한 그림은 다음과 같습니다

이 아니 여기,이 정규식과 모든 어려운 일이 아니다 그냥 때문에
#!/usr/bin/perl 

use strict; use warnings; 

use constant RIGHT_MARGIN => 52; 

my $para = "When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer. This lets other people know that you have received a good answer to your question. Doing this is helpful because it shows other people that you're getting value from the community."; 

my ($wrapped, $line) = (q{}) x 2; 

while ($para =~ /(\S+)/g) { 
    my ($chunk) = $1; 
    if ((length($line) + length($chunk)) >= RIGHT_MARGIN) { 
     $wrapped .= $line . "\n"; 
     $line = $chunk . ' '; 
     next; 
    } 
    $line .= $chunk . ' '; 
} 

$wrapped .= $line . "\n"; 

print $wrapped; 
3

: 치환 후 줄 바꿈을 삽입

$str =~ s/(.{0,46} (?: \s | $))/$1\n/gx; 

최대 46 자 (OP 예제와 일치) 뒤에 공백 또는 문자열의 끝이옵니다. g 수정자는 전체 문자열에서 작업을 반복합니다.

관련 문제