gpt4 book ai didi

regex - 使用正则表达式匹配模式并存储到数组中

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

我有一个类似的帖子(见 other post),但从那时起我想做的事情略有不同。我正在使用与该问题相同的正则表达式匹配 /79(week\d+[a-z])/i

我有一个包含六行的文件,每行都有不同的路径。例如,包含字符串“cat”的 3 行和包含字符串“dog”的 3 行。

文件.txt

/mypath/sd-urt7-dfc-adfj345h-d0-79week48a-DFC-lk-my_cat.text  
/mypath/sd-urt7-afd-parent-79week46d-AFD-lk-my_cat.text
/mypath/sd-urt7-ert-parent-79week50c-ERT-lk-my_cat.text
/mypath/sd-urt7-dfc-adfj345h-d0-79week48a-DFC-lk-my_dog.text
/mypath/sd-urt7-afd-parent-79week46d-AFD-lk-my_dog.text
/mypath/sd-urt7-ert-parent-79week49b-ERT-lk-my_dog.text

我想从每个路径中取出“weekxxX”部分并将其打印到文件中。这是我目前所拥有的:

use strict;
use warnings;
use feature qw(say);
use autodie;

open (my $fh, '<', "file.txt") or die "Couldn't open `file.txt`\n";

foreach my $line (<$fh>){ #goes through each line in the file

chomp $line; #chomps new line character from each line

if ($line =~ /cat/) { #if the path includes string "cat"
#use the regex at top of post to get weekxxX of each
#path containing cat and print all 3 weekxxX into
#another file called cat.

open (my $cat, '>', "cat.txt") or die;
print $cat "";
close $cat;

}
elsif ($line =~ /dog/) { #otherwise if the path includes string "dog"3

#use the regex at top of post to get weekxxX of each
#path containing cat and print all 3 weekxxX into
#another file called dog.

open (my $dog, '>', "dog.txt") or die;
print $dog "";
close $dog;
}
}
close $fh;

我认为这可以通过在所有三个路径上使用正则表达式来完成(取决于它是狗还是猫),将所有三周以 weekxxX 格式推送到一个数组中,然后将该数组打印到文件中?我真的不确定如何实现这一点。

最佳答案

use warnings;
use strict;
use feature 'say';
use autodie qw(open);

my $file = shift // die "Usage: $0 filename\n"; #/

# Patterns that determine what file to write to
my ($p1, $p2) = qw(cat dog);

# Open output files, one for each pattern
my %fh_out = map { open my $fh, '>', "$_.txt"; $_ => $fh } ($p1, $p2);

open my $fh, '<', $file;

while (<$fh>) {
if ( my ($week, $type) = /79(week\d+[a-z]).*?($p1|$p2)/i ) {
say {$fh{$type}} $week;
}
}

关于regex - 使用正则表达式匹配模式并存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59474021/

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