简体   繁体   English

匹配模式:正则表达式 - perl

[英]Matching a pattern : regex - perl

If I want to find in this file all instances of the words USER and PASS and then put the number of times they appear into the two variables respectively, how would I go about that? 如果我想在这个文件中找到USER和PASS这两个单词的所有实例,然后将它们出现的次数分别放入两个变量中,我该如何处理呢? Thanks! 谢谢!

open MYFILE, '<', 'source_file.txt' or die $!;
open OUTFILE, '>', 'Header.txt' or die $!;

$user = 0;
$pass = 0;

while (<MYFILE>) { 
    chomp;

    my @header = split (' ',$_);
    print OUTFILE "$linenum: @header\n\n";

    if (/USER/ig) {
        $user++;
    }

    if (/PASS/ig) {
        $pass++;
    }
}

Above is the new code and it works. 以上是新代码,它的工作原理。 I set my variables equal to 0 and used the ++ incrementor on the variables. 我将变量设置为0并在变量上使用++ incrementor。 But I am still open to suggestions perhaps on expanding my regex's capabilities? 但我仍然愿意接受有关扩展我的正则表达能力的建议吗? (if that makes sense) (如果这是有道理的)

You could simply do. 你可以干脆做。

my $user = 0;
my $pass = 0;

while (<MYFILE>) { 
     chomp;
     my @header = split ' ', $_;
     print OUTFILE "$linenum: @header\n\n";

     $user++ if /user/ig;
     $pass++ if /pass/ig;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM