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

前端 未结 8 2132
礼貌的吻别
礼貌的吻别 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:18

    You can combine your regexes with the alternation operator |, as in: /pattern1|pattern2|pattern3/

    Obviously, it won't be very maintainable if you put all of them in a single line, but you've got options to mitigate that.

    • You can use the /x regex modifier to space them nicely, one per line. A word of caution if you choose this direction: you'll have to explicitely specify the space characters you expect, otherwise they'd be be ignored because of the /x.
    • You can generate your regular expression at run-time, by combining individual sources. Something like this (untested):

      my $regex = join '|', @sources;
      while (<>) {
          next unless /$regex/o;
          say;
      }
      

提交回复
热议问题