如何返回 Perl(或C++)中以某些字符开头和结尾的所有字符



注意:我在Linux上运行Perl 5

目前正在做一个项目,我必须输入几个单词,然后返回以"d"开头并以"e"结尾的单词。我没有使用预先完成的列表,例如,我在控制台中输入完成、碟子、圆顶和死亡。我希望它返回完成和圆顶,但不是其他单词。我希望得到如何在Perl中做到这一点的帮助,但如果Perl不起作用,C++会有所帮助。

perl -ne ' print if /^d/i && /e$/i ' < words

由于您使用的是 Linux,所以使用 grep(1) 可能更简单:

grep -i '^d.*e$' < words

这在 Perl 中几乎是微不足道的:

$ perl -nE 'say "ok" if /^d.*e$/i'
Done
ok
Dish
Dome
ok
Death

它从 STDIN 读取,say s ok 如果行匹配。这在调试正则表达式时很有用。您只想输出匹配的行,因此您可以简单地将say "ok"替换为say

$ perl -nlE 'say if /^d.*e$/i' words

words是你的Words文件的文件名。它神奇地读取其线条。该正则表达式匹配的简短说明:

^    # start of the line
d    # the literal character 'd' (case-insensitive because of the i switch)
.*   # everything allowed here
$    # end of the line

我不经常回答perl问题,但我认为这可以解决问题。

my @words = ...;
@words = grep(/^d.*e$/i, @words);

grep 使用正则表达式来过滤单词。

怎么样:

#!/usr/bin/perl -Tw
use strict;
use warnings;
for my $word (@ARGV) {
    if ( $word =~ m{A d .* e z}xmsi ) {
        print "$wordn";
    }
}

最新更新