regex - 将包含连续段落的字符串拆分为左对齐的行列

标签 regex perl string

在 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/

相关文章:

javascript - 正则表达式来选择引号中的所有空格?

python - 将 Perl 正则表达式转换为 python 正则表达式

java - 如何完全替换一个数字而不中间修改?

java - 如何在for循环中向空字符串添加值?

java - 具有正则表达式支持的 StringBuilder 的 replaceAll?

regex - Sublime Text - 用于搜索和替换的正则表达式

perl - Perl 5 中 `write` 和 `format` 的替代品是什么?

perl - 如果向 STDERR 写入任何内容,就会死掉吗?

php - 如何找到相似的产品

javascript - 变量不区分大小写的正则表达式匹配javascript