gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:38:18 25 4
gpt4 key购买 nike

我被这个正则表达式困住了。它匹配我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com