简体   繁体   English

如何在perl中指定段落数

[英]How to specify number of paragraphs in perl

I Want to find number of occurrences of new line in perl using regex. 我想使用正则表达式在perl中查找新行的出现次数。 How to define number of occurrences of newline in perl. 如何在perl中定义换行符的出现次数。

For example I have text containing 例如,我有文字包含

dog
cat
other 23 newlines
puppy
Kitten

I am able to do regex using notepad Find "(dog)((?:.*[\\r\\n]+){25})(\\w.*)" and replace with "\\1 = \\3 \\2" EDIT 我可以使用记事本Find "(dog)((?:.*[\\r\\n]+){25})(\\w.*)"replace with "\\1 = \\3 \\2"正则表达式编辑

Important thing is that, How to find what is on paragraph 25 from dog. 重要的是,如何从狗身上找到第25段的内容。 More simpler way. 更简单的方法。 How to shorten this find string 如何缩短此查找字符串

(dog)(.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+.*[\r\n]+)(.*)

what is the alternative to specific numbers of new lines in Perl? Perl中特定数量的新行的替代方案是什么?

By mistake posted on superuser, Now Moved here. 错误发布在超级用户身上,Now Moved here。

You can skip the lines when reading the input: 您可以在阅读输入时跳过这些行:

while (<>) {
    if (/dog/) {
        <> for 1 .. 24;
        print scalar <>;
    }
}

Or, if the whole string is the input, you can use a non-capturing group: 或者,如果整个字符串是输入,则可以使用非捕获组:

my ($puppy) = $string =~ /dog(?:.*\n){25}(.*)/;
print $puppy;

In a regex, a dot doesn't match a newline (unless the /s modifier is used). 在正则表达式中,点与换行符不匹配(除非使用/s修饰符)。

You can use the tr/// operator (see perlop ) to count the number of occurrences of a single character. 您可以使用tr///运算符(请参阅perlop )来计算单个字符的出现次数。

#!/usr/bin/perl
use warnings;
use strict;

my $string = 'dog
cat
other 23 newlines
puppy
Kitten';

print $string =~ tr/\n//, "\n";

Output: 输出:

4

这就是我想要的答案。

perl -i.bak -pe "BEGIN{undef $/;} s/(dog)(.*[\r\n]+){23}(.*)/$1 = $3/smg" 1.rtf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM