Regex 如何使用perl正则表达式搜索特定文本?
在下面列出的以下字符串中,我只需要搜索第一个字符串Regex 如何使用perl正则表达式搜索特定文本?,regex,perl,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 测试A您可能需要使用: 仅匹配准
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
测试A您可能需要使用:
仅匹配准确的字符串“测试A”
。但问题仍然存在——如果您要查找特定字符串,为什么要使用正则表达式?您的问题相当模糊。假设数据与您提供的匹配,并且您希望逐行筛选文件,则可以使用$
锚定:
#!/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;
}
#/usr/bin/perl
使用警告;
严格使用;
my$infie='in.txt';
打开我的$input,“您可能根本不需要复杂的Perl,因为您可以通过grep轻松地完成这项工作,如下所示:
grep "Test A" yourfile | egrep -v "B|C|D""
为什么你想要第一个字符串而不是其他的?规则是什么?最好将正则表达式和您目前使用的测试数据样本放入问题中。从您已有的代码开始时更容易帮助您。每一个代码都是一个单独的字符串?或者这些行在一个文件中,而您只想匹配其中一行?到目前为止,你的问题还不清楚。谢谢你尽我所能理解这个问题,你的解决方案有效。。。。
grep "Test A" yourfile | egrep -v "B|C|D""