Regex 用正则表达式去掉中间的首字母

Regex 用正则表达式去掉中间的首字母,regex,perl,Regex,Perl,我知道我在做一些愚蠢的事情,但我很累,我显然只是看不到而已。我有以下脚本: #!/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"; } 运行此脚本时,我得到以下输出

我知道我在做一些愚蠢的事情,但我很累,我显然只是看不到而已。我有以下脚本:

#!/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
Before:johnq.Public
之后:约翰。公共问题是

". " =~ /\.\b/ or print "There is no word boundary between a dot and a space.\n"
问题是

". " =~ /\.\b/ or print "There is no word boundary between a dot and a space.\n"

我想我会选择在空白处分割名称,只选择第一个和最后一个字段

像这样:

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

我想我会选择在空白处分割名称,只选择第一个和最后一个字段

像这样:

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

我是个白痴。谢谢你的帮助;只要我能接受答案,我会的。我是个白痴。谢谢你的帮助;只要我能接受这个答案,我会的。