简体   繁体   中英

How to specify number of paragraphs in perl

I Want to find number of occurrences of new line in perl using regex. How to define number of occurrences of newline in 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

Important thing is that, How to find what is on paragraph 25 from dog. 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?

By mistake posted on superuser, 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).

You can use the tr/// operator (see perlop ) to count the number of occurrences of a single character.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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