Regex perl正则表达式-多模式匹配,可选匹配

Regex perl正则表达式-多模式匹配,可选匹配,regex,perl,pattern-matching,Regex,Perl,Pattern Matching,我被这个正则表达式卡住了。它与我的3个文件名中的2个匹配。如果可能的话,需要帮助获得所有三个。 我还想在扩展名.edu | net之前,将这些值中的一个abc | def | ghi以及ucsb | tech区域名称提取到变量中 如果可能的话,我想一次完成。谢谢 /home/test/abc/.last_run_dir /home/test/def/.last_file_sent.mail@wolverine.ucsb.edu /home/test/ghi/.last_file_sent.dp3

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

如果可能的话,我想一次完成。谢谢

/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';

打开我的$FILE,“正则表达式中w{3}强制它查找下一个点单词dot之后的部分:

[.](\w+)[.].*
一个简单的修复方法是将此设置为可选。但当您这样做时,您可能需要首先锁定它。*:指定它可以是任何字符串,但不能是句点。(顺便说一句,这通常是一个很好的做法。)


编辑:我发现我的解决方案可能需要一些测试来检查周期是否在正确的位置,仅供参考

您的正则表达式需要两个“.”实例才能匹配。如果第二个选项是可选的,请使用[。]

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

你可以这样做:

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

我喜欢你提供的解决方案提示:)谢谢。另外,如何打印出所有可能的匹配项?包括可选的?@jdamae
my($dir,$dom)=$line=~m#home/test/(\w{3})[^.]*([.](\w+[.].*)?
伙计们,我还是被卡住了。我试过你的建议。我需要提取我在问题中描述的那些名字
ucsb
tech
或将在
.edu
.net
之前获取名称的东西,这只是我检查文件所需的一个小实用程序。尝试学习perl。谢谢。
$line =~ m#home/test/(\w{3}).*[.](\w+)[.]?.*#;
#!/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/.last_file_sent.mail@wolverine.ucsb.edu
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