Regex perl正则表达式匹配标量加标点
我有标量(表中的列),它有一个或两个用逗号分隔的电子邮件地址。比如Joek@xyznco.com, jrancher@candyco.us“或者”jsmith@wellingent.com,mjones@wellingent.com'对于其中一些记录,我需要删除一个坏的/旧的电子邮件地址和尾随的逗号(如果存在) 如果jmsith@wellingent不再有效如何删除该地址和尾随逗号 这只会删除地址,但保留逗号Regex perl正则表达式匹配标量加标点,regex,perl,Regex,Perl,我有标量(表中的列),它有一个或两个用逗号分隔的电子邮件地址。比如Joek@xyznco.com, jrancher@candyco.us“或者”jsmith@wellingent.com,mjones@wellingent.com'对于其中一些记录,我需要删除一个坏的/旧的电子邮件地址和尾随的逗号(如果存在) 如果jmsith@wellingent不再有效如何删除该地址和尾随逗号 这只会删除地址,但保留逗号 my $general_email = 'jsmith@wellingent.com,
my $general_email = 'jsmith@wellingent.com,mjones@wellingent.com';
my $bad_addr = 'jsmith@wellingent.com';
$general_email =~ s/$bad_addr//;
谢谢您的帮助。如果不使用正则表达式,但使用列表拆分,您可能会过得更好:
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
过滤该错误地址<代码>将剩余元素重新连接成字符串
上述代码打印:
第一:you@example.org
最后:me@example.org
中间:me@example.org,other@eample.org
我要替换
!m/$bad/
与$\ne$bad
一起使用,以避免误报,但除此之外,这似乎是最可靠的解决方案。