在PERL字符串中交换两个相邻单词的更好方法是什么?

时间:2017-06-24 05:31:07

标签: regex perl

我有一个奇怪的案例,我在写的游戏中输入了两个错误的名字。他们互相镜像。例如,亨利·帕特里克和帕特里克·亨利,我想把它们换成我写的错误代码块。

现在下面的PERL代码会这样做,但临时替换字符串heinous-hack-string是一个黑客。有更优雅的做事方式吗?

##################
#nameflip.pl
#
# this flips names where I mistakenly switched first-last and last-first
#

use strict;
use warnings;

my $mystr = "There's this guy named Henry Patrick, and there's another guy named Patrick Henry, " . 
  "and I confused them and need to switch them now!";

print "Before: $mystr\n";

print "After: " . stringNameSwitch($mystr, "Patrick", "Henry") . "\n";

##############################
# awful hack of a subroutine.
#
# what regex would do better?
#
# right now I just want to switch (name1 name2) <=> (name2 name1)

sub stringNameSwitch
{
  my $temp = $_[0];
  $temp =~ s/$_[1] +$_[2]/heinous-hack-string/i;
  $temp =~ s/$_[2] +$_[1]/$_[1] $_[2]/i;
  $temp =~ s/heinous-hack-string/$_[2] $_[1]/i;
  return $temp;
}

1 个答案:

答案 0 :(得分:3)

或许这样吗? 分支重置构造(?|...)允许将两个名称捕获到$1$2,无论其出现顺序如何。

use strict;
use warnings 'all';

my $mystr = <<END;
There's this guy named Henry Patrick,
and there's another guy named Patrick Henry,
and I confused them and need to switch them now!
END

print name_switch($mystr, qw/ Henry Patrick /);

sub name_switch {
    my ($s, $n1, $n2) = @_;

    $s =~ s/\b(?|($n1)\s+($n2)|($n2)\s+($n1))\b/$2 $1/gr;
}

输出

There's this guy named Patrick Henry,
and there's another guy named Henry Patrick,
and I confused them and need to switch them now!