在 Perl 中,在一个没有换行符的大长字符串中处理一段文本,我如何使用拆分和 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"
谢谢,
本
最佳答案
当然,使用 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;
关于regex - 将包含连续段落的字符串拆分为左对齐的行列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3481279/