How can I efficiently match many different regex patterns in Perl?

前端 未结 8 2128
礼貌的吻别
礼貌的吻别 2020-12-18 07:52

I have a growing list of regular expressions that I am using to parse through log files searching for \"interesting\" error and debug statements. I\'m currently breaking th

8条回答
  •  天涯浪人
    2020-12-18 08:31

    One possible solution is to let the regex state machine do the checking of alternatives for you. You'll have to benchmark to see if the result is noticeably more efficient, but it will certainly be more maintainable.

    First, you'd maintain a file containing one pattern of interest per line.

    Failed in routing out
    Agent .+ failed
    Record Not Exist in DB
    

    Then you'd read in that file at the beginning of your run, and construct a large regular expression using the "alternative" operator, "|"

    open(PATTERNS,";
    close PATTERNS or die $!;
    chomp @patterns;
    $matcher = join('|', @patterns);
    
    while () {
        print if $_ =~ $matcher;
    }
    

提交回复
热议问题