简体   繁体   中英

How do I insert multilines in Perl regexps?

我正在使用正则表达式来移动文本块,但它仅删除单行-要删除多行,我应该包括哪些内容?

You are probably looking for /<!--\\[perl\\](.*?)-->/s

Use option switch /s

It treats string as a single line.

"." (dot) will match any character at all, including newline.

There are two things that often trip people up when trying to make regexes work across multiple lines.

The first is the fact that a dot in a regex doesn't match a newline unless you use the /s option on your m// or s/// operator.

The second is that if you're processing a text file a line at a time (perhaps with while (<$filehandle>) { ... } ) then each time round the loop you only have a single line of text to match against. You'll need to read the whole file in at once (perhaps using $text = do { local $/; <$filehandle>}; ).

#!/usr/bin/env perl

use strict; use warnings;

{
    local $/ = '-->';
    while (my $chunk = <DATA>) {
        $chunk =~ s/<!-- \[perl\] (.*) --> \z//sx;
        print $chunk;
    }
}

__DATA__
<!--[perl]

my $x = 5;
my $y = 3;
say $x + $y

-->

<!--[not]

const char *s = "This is not Perl ;-)";

-->

By judiciously altering the input record separator , you can ensure that every chunk you read ends with the string "-->" . Then, it's a matter of ensuring . can match line endings by supplying the /s flag to your substitution operator.

Output:

<!--[not]

const char *s = "This is not Perl ;-)";

-->

You can also remove leading/trailing space from the chunks if that matters.

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