用于快速搜索数组中元素的文件的Perl习语

时间:2013-12-27 02:46:06

标签: regex arrays perl grep

搜索字符串或整个文件以查找数组元素的Perl习惯用法是什么? E.g:

my @array = qw(word, test, ...);
my $string = ".......";

我想在word内搜索testwords(也可以是tester$string等)并返回找到的内容(即小组赛。)

我搜索了文档,似乎map + grep就像我需要的那样,但我无法想出它的代码。 Perl非常有趣,有时候我完全无能为力。 :)

使用map中的一个示例:

my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;

我想我可以将字符串拆分为数组grep。我是对的吗?

grep { @array } @string;  # something like grep {/(word|test)/} @string but I want to use array

2 个答案:

答案 0 :(得分:6)

my @word_roots = qw( word test );

my $pat = join '|', map quotemeta, @word_roots;
my $re = qr/\b(?:$pat)\w+\b/;

my @matches = $string =~ /($re)/g;

答案 1 :(得分:3)

re.pl 会话中的内容如何:

$ my @array = qw(word test)
$VAR1 = 'word';
$VAR2 = 'test';

$ my $string = ' the word is test, I said'
 the word is test, I said

$ my @match_array = map { $string =~ /\b($_)\b/ } @array
$VAR1 = 'word';
$VAR2 = 'test';

\b$_\b周围的括号捕获map内的正则表达式中的匹配。

\b确保我们只匹配单词是自己找到的(如“test”或“word”),而不是包含字符“test”或其中的“word”的单词“胆小鬼”或“最聪明”。有关\b

的详细信息,请参阅http://www.regular-expressions.info/wordboundaries.html
相关问题