2010-08-13 124 views
3

在Perl中,如果使用段落長度爲1的大字符串且不帶換行符,那麼如何使用拆分和RegEx(或其他)在一個字邊界處將段落分成幾乎相同大小的塊,以便以等寬字體顯示?將包含連續段落的字符串拆分爲左對齊的行列

例如,我該如何改變這種:

"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修改器重複整個字符串的操作。

相關問題