我最近创建了一个Perl脚本,用以下代码搜索以D和E开头的单词:
$infile = 'words.txt';
open(IN, $infile);
$count = 0;
while ($word = <IN>) {
chomp($word);
if ($word =~ /^d\w*e$/i) {
print "$word\n";
$count++;
}
}
print "$count\n";
Run Code Online (Sandbox Code Playgroud)
我最近决定分叉代码并创建一个脚本,搜索一个单词,这个单词是六个字母,单词中的字母是按字母顺序排列的(A到Z).我打算使用位于usr/share/dict/words的Unix标准字典,而不是使用words.txt.如何通过修改此代码来实现此目的?
看起来你真正需要的是一种算法,用于检查给定单词中的字母是否按字母顺序排列.有几种方法,但是这个子程序的工作原理是将单词拆分为其组成字符列表,对列表进行排序并重新组合.如果结果与原始单词匹配,则该单词已经排序.
use strict;
use warnings;
use feature 'fc';
for (qw/ a ab ba cab alt effort toffee /) {
print "$_\n" if in_alpha_order($_);
}
sub in_alpha_order {
my $word = fc(shift);
my $new = join '', sort $word =~ /./g;
return $new eq $word;
}
Run Code Online (Sandbox Code Playgroud)
产量
a
ab
alt
effort
Run Code Online (Sandbox Code Playgroud)
如果你真的想在正则表达式中这样做,你可以建立一个像
a(?=[a-z]) | b(?=[b-z]) | c(?=[c-z]) ...
Run Code Online (Sandbox Code Playgroud)
这是一个以这种方式工作的程序.其输出与上述输出相同.
use strict;
use warnings;
my $regex = join '|', map "${_}(?=[$_-z])", 'a'..'z';
$regex = qr/^(?:$regex)*.$/i;
for (qw/ a ab ba cab alt effort toffee /) {
print "$_\n" if $_ =~ $regex;
}
Run Code Online (Sandbox Code Playgroud)