Perl:如何匹配字符串中的特定字符?

时间:2013-09-10 15:45:36

标签: regex perl match

我有两个文件,File1和File2。我想比较这两个文件之间的行和打印。但是我没有找到匹配特定字符串的方法。我尝试了下面的编码,但它打印出意想不到的结果。
我想打印File2数据(例如b05 * ldt * 10ud0e0),当它与File1的名称匹配时(例如 ldt )。对于那些在File1中带星号*的数据(例如b05can03 * n0b5),*可以是任何字符。为了匹配,它必须匹配File2. *中的*的头部和尾部,它将打印出b05can03un0b5。并且打印必须遵循File1的顺序。有谁可以给​​我这方面的建议?

File1中

LDT
b05dcc00
MNY
b05can03 * n0b5
b05mdd04 * n9c9

文件2

/* To start: b05afn10ud0b0 */  
/* To start: b05dcc00ud0c0 */  
/* To start: b05ldt10ud0e0 */  
/* To start: b05dcc10ud0i0 */  
/* To start: b05afn10ud0m0 */  
/* To start: b05afn10ud0s0 */  
/* To start: b05mny00ud0b5 */  
/* To start: b05mny00ud0d3 */  
/* To start: b05mdd04un9c9 */  
/* To start: b05ahn00ud0j5 */  
/* To start: b05mny00ud0m7 */  
/* To start: b05can03un0b0 */  
/* To start: b05can03un0b5 */  

编码:

my ( @arr1, @arr2 );

@arr1 = <File1>; 
@arr2 = <File2>;

foreach my $line1 (@arr1) {
    foreach my $line2 (@arr2) {
        if ( $line1 =~ $line2 && $line1 =~ m/^\w+(\W)\w+(.*)/ ) { 
            print "$line2\n";
        }   
    }     
}

预期结果:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9

3 个答案:

答案 0 :(得分:0)

open my $File1, "<", "File1" or die $!;
open my $File2, "<", "File2" or die $!;

my @arr1 = map {
  s|\s+$||g;
  s|\*|.|g ? qr/($_)/ : qr/(\w*$_\w*)/;
}
<$File1>;

my $str = do { local $/; <$File2> };

print "$_\n" for map $str =~ /$_/g, @arr1;

输出:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9

答案 1 :(得分:0)

这应该做你想要的......

#!/usr/bin/perl

use strict; 
use warnings;

use autodie;
use feature qw(say);

my $file1 = "f1.txt";
my $file2 = "f2.txt";

open my $fh1, "<", $file1;
open my $fh2, "<", $file2;

my @wanted = map { chomp; qr/$_/; } <$fh1>;
close $fh1;

while (my $line = <$fh2>) {
    chomp $line;
    for my $wanted (@wanted) {
        say "matched: $line" if $line =~ /$wanted/;
    }   
}
close $fh2;

答案 2 :(得分:0)

如果File2不是太大,你可以将它篡改成一个变量,然后在整个字符串上全局执行有序匹配:

use strict;
use warnings;

my $file2 = do { local $/; local @ARGV = pop; <> };

while (<>) {
    chomp;
    s/\*/./g;
    print "$1\n" while $file2 =~ m!(?:/\*\s+To\s+start:\s+)(.*$_.*)(?:\s+\*/)!g;
}

用法:perl script.pl File1 File2

输出:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9

希望这有帮助!