【问题标题】:Filter group of pattern inside array in perl在perl中过滤数组内的模式组
【发布时间】:2016-12-29 02:52:21
【问题描述】:
如何使用正则表达式过滤和收集数组内的一组模式?
搜索模式是.include 'pathToFile',其中pathToFile 必须存储到@include 数组中。
my @include = grep {$4 if /^\s*\.(inc)(l(ude)?)?\s+'(\S+)'/i} @fileContent;
不幸的是,我的代码不只存储 $4 这是包含文件路径。我怎样才能让它发挥作用?
【问题讨论】:
标签:
arrays
regex
perl
filter
【解决方案1】:
你需要map@fileContent中的每一项来捕获$4,然后grep才能找到匹配的:
my @include = grep {!/^$/} map {/^\s*\.(inc)(l(ude)?)?\s+'(\S+)'/i && $4} @fileContent;
顺便说一下,前三个捕获组是多余的,所以你可以只用捕获组$1重写正则表达式:
my @include = grep {!/^$/} map {/^\s*\.inc(?:l(?:ude)?)?\s+'(\S+)'/i && $1} @fileContent;