我想从我文件中的字符串中删除单词Z或ZN和LVT,但我无法得到它。有人可以查看我的代码。
输入
abchsfk/jshflka/ZN (cellLVT)
asjkfsa/sfklfkshfsf/Z (mobLVT)
asjhfdjkfd/sjfdskjfhdk/hsakfshf/Z (celLVT)
asjhdjs/jhskjds/ZN (abcLVT)
shdsjk/jhskd/ZN (xyzLVT)
输出
abchsfk/jshflka cell
asjkfsa/sfklfkshfsf mob
asjhfdjkfd/sjfdskjfhdk/hsakfshf cel
asjhdjs/jhskjds abc
shdsjk/jhskd xyz
CODE:
if ($line =~ /LVT/ && ($line =~ /ZN/ || $line =~ /Z/) )
#### matches the words LVT and ( Z or ZN)
{
my @names = split / /, $line; ##### splits the line
$names[2] =~ s/\/Z|/ZN//g; #### remove Z or ZN
$names[3] =~ s/\(|LVT\)//g ; #### remove LVT & braces
print OUT " $names[2] $names[3] \n"; #### print
}
答案 0 :(得分:2)
问题是匹配顺序:s/\/Z|\/ZN//g
(代码中缺少第二个反斜杠!)。您应首先匹配较长的字符串,否则Z将匹配,N将不会被删除。
但更简单的方法是:只需使用\/ZN?
:
#!/usr/bin/perl
use warnings;
use strict;
while (my $line = <DATA>) {
if ($line =~ /LVT/ && $line =~ /ZN?/) {
my @names = split ' ', $line;
$names[0] =~ s/\/ZN?//g;
$names[1] =~ s/\(|LVT\)//g;
print "$names[0] $names[1]\n";
}
}
__DATA__
abchsfk/jshflka/ZN (cellLVT)
asjkfsa/sfklfkshfsf/Z (mobLVT)
asjhfdjkfd/sjfdskjfhdk/hsakfshf/Z (celLVT)
asjhdjs/jhskjds/ZN (abcLVT)
shdsjk/jhskd/ZN (xyzLVT)