2010-08-13 3 views
3

En Perl, travailler avec un paragraphe de texte dans une grande chaîne longue sans sauts de ligne, comment puis-je utiliser un split et RegEx (ou autre chose) diviser le paragraphe en morceaux d'environ la même taille à une limite de mot, pour l'affichage dans une police à espacement fixe?Fractionner une chaîne contenant un paragraphe continu dans une colonne de lignes alignées à gauche

Par exemple, comment puis-je modifier ceci:

"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." 

dans ce:

"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" 

Merci, Ben

Répondre

4

Bien sûr, utilisez Text::Wrap. Mais, voici une illustration juste pour le plaisir de celui-ci:

#!/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

Juste depuis son pas ici, ce n'est pas si difficile avec une expression régulière:

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

La substitution insère un saut de ligne après jusqu'à 46 caractères (correspond à l'exemple OP) suivi d'un espace ou de la fin de la chaîne. Le modificateur g répète l'opération sur toute la chaîne.

Questions connexes