我知道我在这里做了一些蠢事,但我很累,而我显然只是没有看到它。我有以下脚本:
#!/usr/bin/perl
use strict;
use warnings;
my @names = (
"John Q. Public",
"James K Polk"
);
foreach (@names)
{
print "Before: $_\n";
s/\b[A-Z]\.?\b//;
print "After: $_\n";
}
当我运行此脚本时,我得到以下输出:
Before: John Q. Public
After: John . Public <== Why is the period still here?
Before: James K Polk
After: James Polk
请注意,在 John Q. Public 示例中,会留下句号。是不是可选的匹配参数(?
)贪心?根据{{3}}:
?匹配1或0次
这个时期不应该随着中间的首字母而消失吗?我在这里缺少什么?
答案 0 :(得分:4)
问题是
". " =~ /\.\b/ or print "There is no word boundary between a dot and a space.\n"
答案 1 :(得分:1)
我想我会选择在空格上拆分名称,只选择第一个和最后一个字段。
像这样:
use strict;
use warnings;
my @names = ("John Q. Public", "James K Polk");
foreach (@names) {
print "Before: $_\n";
$_ = join ' ', (split)[0, -1];
print "After: $_\n";
}
<强>输出强>
Before: John Q. Public
After: John Public
Before: James K Polk
After: James Polk