regex - perl regex - 多种模式匹配,可选匹配

标签 regex perl pattern-matching

我被这个正则表达式困住了。它匹配我的 3 个文件名中的 2 个。如果可能的话,需要帮助获得所有三个。 我还想在扩展名 .edu | 之前提取这些值 abc|def|ghi 以及 ucsb|tech 区域设置名称之一。 .net 到变量中。

如果可能的话,希望一次性完成此操作。谢谢。

/home/test/abc/.last_run_dir
/home/test/def/.last_file_sent.mail@wolverine.ucsb.edu
/home/test/ghi/.last_file_sent.dp3.tech.net

它没有拿起第一行:

/home/test/abc/.last_run_dir

正则表达式:

$line =~ m#home/test/(\w{3}).*[.](\w+)[.].*#

代码:

my $file = 'Index.lst';
open my $FILE, '<', $file or die "unable to open '$file' for reading: $!";
while (my $line = <$FILE>) {
    chomp($line);
    if ($line =~ m#home/test/(\w{3}).*[.](\w+)[.].*#) {
        open my $file2, '<', $line or die "unable to open '$file' for reading: $!";
        while(my $line2 = <$file2>) {
        print "$line2";
        }
        close $file2;
    }
} #end while
close $FILE;

另外,我如何打印出可能的匹配项?如果它们是可选的?

最佳答案

你可以这样做:

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

while(my $line=<DATA>) {
    chomp($line);
    if ($line =~ m#home/test/(\w{3})/\.(\w+)(?:.*\.(\w+)\.[^.]+)?|$#) {
        print "$line\n";
        print "1=$1\t2=$2\t3=$3\n";
    }
}

__DATA__
/home/test/abc/.last_run_dir
/home/test/def/.last_file_sent.mail@wolverine.ucsb.edu
/home/test/ghi/.last_file_sent.dp3.tech.net

输出:

/home/test/abc/.last_run_dir
1=abc   2=last_run_dir  3=
/home/test/def/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f31737e6c6b407976737a406c7a716b31727e76735f687073697a6d76717a316a7c6c7d317a7b6a" rel="noreferrer noopener nofollow">[email protected]</a>
1=def   2=last_file_sent    3=ucsb
/home/test/ghi/.last_file_sent.dp3.tech.net
1=ghi   2=last_file_sent    3=tech

关于regex - perl regex - 多种模式匹配,可选匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4414680/

相关文章:

perl 解析多个字符串的文件

algorithm - 应该使用什么相似性度量来对这些序列进行分类?

Scala 可选模式匹配

java - 正则表达式测试 md5sum 文件格式

regex - 为什么我不能连接在 qr 下编译和运行时评估的模式?

javascript 正则表达式 - 将所有实例替换为一个

perl - 使用blowfish 或AES 在Perl 中加密/解密二进制文件?

java - 使用 Java 正则表达式模式解析字符串?

regex - 有没有办法使用 sed 只删除完全匹配的字符串?

python - 我可以多次匹配正则表达式中的 or 表达式吗?