perl正则表达式匹配标量加标点符号

时间:2017-12-02 14:21:36

标签: regex perl

我有scalars(表中的列),其中有一个或两个电子邮件地址用逗号分隔。例如' Joek@xyznco.com,jrancher@candyco.us'或者' jsmith @ wellingent.com,mjones @ wellingent.com'对于其中几条记录,我需要删除错误/旧的电子邮件地址和尾随逗号(,如果存在)

如果jmsith @ wellingent不再有效,我该如何删除该地址和尾随逗号?

这只会删除地址但会留下逗号。

my $general_email = 'jsmith@wellingent.com,mjones@wellingent.com';
my $bad_addr = 'jsmith@wellingent.com';

$general_email =~ s/$bad_addr//;

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如果没有正则表达式但是列表拆分可能会更好:

use strict;
use warnings;

sub remove_bad {
    my ($full, $bad) = @_;
    my @emails = split /\s*,\s*/, $full;  # split at comma, allowing for spaces around the comma
    my @filtered = grep { $_ ne $bad } @emails;
    return join ",", @filtered;
}

print 'First: ' , remove_bad('me@example.org, you@example.org', 'me@example.org'), "\n";
print 'Last: ', remove_bad('me@example.org, you@example.org', 'you@example.org'), "\n";
print 'Middle: ', remove_bad('me@example.org, you@example.org, other@eample.org', 'you@example.org'), "\n";

首先,split逗号中的错误电子邮件地址列表,创建一个数组。使用grep过滤掉,以删除错误的地址。 join其余元素返回字符串。

以上代码打印:

  

首先:you@example.org

     

最后:me@example.org

     

中间:me @ example.org,其他@eample.org