如何使用perl正则表达式搜索特定文本?

时间:2013-12-01 18:42:32

标签: regex perl

在下面列出的以下字符串中,我只需要搜索第一个字符串..

  test A             <--- only need this string
  test A and test B  <--- don't need this string
  test A and test C  <--- don't need this string
  test A and test D  <--- don't need this string

Perl正则表达式当我只需要上面列出的第一个字符串时,我正在使用返回上面的所有四个字符串。如何过滤掉最后三个字符串并仅获取第一个字符串?

3 个答案:

答案 0 :(得分:1)

你的问题很模糊。假设数据与您提供的数据相符,并且您希望逐行过滤文件,则可以使用$锚点:

#!/usr/bin/perl
use warnings;
use strict; 

my $infile = 'in.txt';
open my $input, '<', $infile or die "Can't open to $infile: $!";

 while (<$input>){       
     chomp;
     print "$_\n" if /test A$/g;
}

$在字符串末尾匹配的位置 - 在这种情况下输入文件的每一行

http://perldoc.perl.org/perlretut.html

答案 1 :(得分:0)

您可能需要使用anchors

/^test A$/

仅匹配完全字符串"test A"。但问题仍然存在 - 为什么要使用正则表达式,如果你正在寻找一个特定的字符串?

答案 2 :(得分:0)

您可能根本不需要Perl的复杂功能,因为您可以使用grep轻松完成此操作,如下所示:

grep "Test A" yourfile | egrep -v "B|C|D""
相关问题