如何匹配不包含单词的字符串?

时间:2016-01-25 06:43:49

标签: perl

说我有这个输入:

Printer: A
Some other lines.
Status: good
Printer: B
Some other lines.
Status: bad

我想使用一个匹配来使打印机名称处于不良状态,' B'在这种情况下。我该怎么做?我尝试了一些,但我不断得到这两个名字。例如:

$ perl -e 'undef $/; $_=<>; /^Printer: (?:\n|.)+?^Status: bad$/; print' input

Printer: A
Some other lines.
Status: good
Printer: B
Some other lines.
Status: bad

4 个答案:

答案 0 :(得分:1)

试试这个:

Error in foreign key constraint of table ev/userfilescategories:
FOREIGN KEY (`user`) REFERENCES `user` (`id`) ON DELETE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=6:
Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. 
Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables.

答案 1 :(得分:0)

我假设你有一个输入文件。试试这个:

my $preline;

while (<>)
{
    chomp;
    if (/^Status: Bad/)
    {
        my $printer = $preline, scalar <>;
        $printer =~ m/^Printer:\s+(.*)/;
        print "$1\n";
        last;
    }
    $preline = $_;
}

输出:

B

答案 2 :(得分:0)

我可能会解决这个问题:

  • 使用正则表达式和地图选择打印机和状态为哈希。
  • 过滤结果,寻找特定的密钥。

这样的事情:

#!/usr/bin/env perl

use strict;
use warnings; 
use Data::Dumper; 

#traverse all of <DATA> extracting pairs of values, that make hash keys. 
my %printer_status = map { m/(?:Printer|Status): (\w+)/ } <>; 
#for debug, print
print Dumper \%printer_status; 

#print the keys of that hash that are 'bad'. 
print join "\n", grep { $printer_status{$_} eq "bad" } keys %printer_status;

现在,为了说明的目的,这是以较长的形式写出来的 - 注意,它假设“打印机”的排序。和&#39;状态&#39;是一致的,没有欺骗。 (无论是关键还是价值)。

这将从STDIN或指定为参数的文件中读取管道数据。给出你的例子,打印出来:

B

现在,正如你所说,你想要一个凝聚成一个衬垫:

perl -e '%p=map {m/(?:Printer|Status): (\w+)/}<>; print join "\n", grep {$p{$_} eq "bad"} keys %p'

答案 3 :(得分:0)

你可以试试这样的事情

#!perl -w

use strict;
use warnings;

my $printerName = "";
while (<DATA>) {
  if (/Printer: (\w+)/) {
    $printerName = $1;
    next;
  }
  if (/Status: (\w+)/){
    my $status = $1;
    print "$printerName, $status\n" if ($status =~ /bad/i);
    next;
  }
}

__DATA__
Printer: A
Some other lines.
Some more other lines.
Status: good
Printer: B
Some other lines.
another line
yet another line
Status: bad