Stopping regex at the first match, it shows two times

89 views Asked by At

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";
}

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.

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?

EDIT:

The value of $row is:

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

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

1

There are 1 answers

2
Borodin On

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