【问题标题】:perl pattern matching in multiline string多行字符串中的 perl 模式匹配
【发布时间】:2014-09-30 18:40:51
【问题描述】:

我有一个包含大约 100 行的变量。我需要打印有 url 的行。

$string = "this is just a test line 1
this is a test line 2
http://somelink1
this is line 4
http://link2
...
...

我只需要打印 url 链接。

如何从 $string 打印所有匹配模式的行。尝试了下面的代码。

my $resu =~ /(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?/, $string;
print $resu;

【问题讨论】:

  • 请展示您的尝试。
  • 如果您没有将所有输入读入一个长字符串中的标量,那么逐行遍历输入并打印所需的行将是一件简单的事情。这是一个 XY 问题。
  • 虽然它已经关闭了一个相关但不重复的问题,但我认为您在正则表达式中寻找的部分是标志:mgc(多行,全局,不要重置位置)。然后在while循环中循环匹配。

标签: regex perl


【解决方案1】:

你需要使用/g Modifier来匹配多行:

use strict;
use warnings;

my $string = <<'END_STR';
this is just a test line 1
this is a test line 2
http://somelink1
this is line 4
http://link2
...
...
END_STR

while ($string =~ m{(.*http://.*)}g) {
    print "$1\n";
}

输出:

http://somelink1
http://link2

但是,如果您要从文件中提取这些数据,最好只逐行读取文件:

while (<$fh>) {
    print if m{(.*http://.*)}g;
}

【讨论】:

    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 2013-06-09
    • 2016-10-23
    • 2012-08-22
    • 2014-05-28
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多