在第一场比赛中停止正则表达式,显示两次 [英] Stopping regex at the first match, it shows two times

查看:65
本文介绍了在第一场比赛中停止正则表达式,显示两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个perl脚本,我有一个简单的正则表达式来捕获数据文件中的一行.该行以IG-XL Version:开头,后跟数据,因此我的正则表达式与该行匹配.

I am writing a perl script and I have a simple regex to capture a line from a data file. That line starts with IG-XL Version:, followed by the data, so my regex matches that line.

if($row =~/IG-XL Version:\s(.*)\;/)
{
    print $1, "\n";
}

假设$1打印出9.0.0.那是我想要的结果.但是,在相同数据文件的另一部分中,也有一个相同IG-XL Version:. $ 1现在打印出两个数据9.0.0.

Let's say $1 prints out 9.0.0. That's my desired outcome. However in another part of the same data file also has a same line IG-XL Version:. $1 now prints out two of the data 9.0.0.

我只希望它与第一个匹配,所以我只能得到一个值.我尝试了/IG-XL Version:\s(.*?)\;/,这是通过添加?来建议的解决方案,因此它将是.*?,但它仍然输出两个.有帮助吗?

I only want it to match the first one so I can only get the one value. I have tried /IG-XL Version:\s(.*?)\;/ which is the most suggested solution by adding a ? so it'll be .*? but it still outputs two. Any help?

$row的值为:

Current IG-XL Version: 8.00.01_uflx (P7); Build: 11.10.12.01.31
Current IG-XL Version: 8.00.01_uflx (P7); Build: 11.10.12.01.31

我想要的期望值是我确实得到的8.00.01_uflx (P7),但是两次.

The desired value I want is 8.00.01_uflx (P7) which I did get, but two times.

推荐答案

在逐行读取文件时执行此操作的唯一方法是保留一个状态标志,该标志记录您是否已经找到该模式.但是,如果您将数据存储在散列中,就像您在您先前的问题中一样,那么这将无关紧要只是用相同的值覆盖哈希元素

The only way to do this while reading the file line by line is to keep a status flag that records whether you have already found that pattern. But if you are storing the data in a hash, as you were in your previous question, then it won't matter as you will just overwrite the hash element with the same value

if ( $row =~ /IG-XL Version:\s*([^;]+)/ and not $seen_igxl_vn ) {
    print $1, "\n";
    $seen_igxl_vn = 1;
}

或者,如果文件很小,您可以将整个内容读到内存中,然后仅搜索每个项目的第一个匹配项

Or, if the file is reasonably small, you could read the whole thing into memory and search for just the first occurrence of each item

我建议您发布一个问题,以显示您的完整程序,您的输入数据和所需的输出,以便我们可以为您提供完整的解决方案,而不是一点一点地看到您的问题

I suggest you should post a question showing your complete program, your input data, and your required output, so that we can give you a complete solution rather than seeing your problem bit by bit

这篇关于在第一场比赛中停止正则表达式,显示两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆