Search code examples
regexperlnon-greedy

Perl regex subsitute last occurrence


I have this input:

AB2.HYNN.KABCDSEG.L000.G0001V00
AB2.HYNN.GABCDSEG.L000.G0005V00

I would like to remove all which finish by GXXXXVXX in the string.

When i use this code:

$result  =~ s/\.G.*V.*$//g;
print "$result \n";

The result is :

AB2.HYNN.KABCDSEG.L000
AB2.HYNN

It seems each time the regex find ".G" it removes with blank . I don't understand.

I would like to have this:

AB2.HYNN.KABCDSEG.L000
AB2.HYNN.GABCDSEG.L000

How i can do this in regex ?


Solution

  • Update:

    After talking in the comments, the final solution was:

    s/\.G\w+V\w+$//;
    

    In your regex:

    s/\.G.*V.*$//g;
    

    those .* are greedy and will match as much as possible. The only requirement you have is that there must be a V after the .G somewhere, so it will truncate the string from the first .G it finds, as long as it is followed by a V. There is no need for the /g modifier here, because any match that occurs will delete the rest of the string. Unless you have newlines, because . does not match newlines without the /s modifier.