Reverse Regular Expression Search

I have a line containing "foo" with numbers. I want to print the number following the last foo in the line. I was told that the only way to do this is to flip the line. It's not very elegant, and I'm surprised Perl has no better way to get the job done. Is there a better way to do this than this?

#!/usr/bin/perl
# works, but is ugly!!!
$string = "foo1 foo3 foo5 bar foo911 baz";
$string = scalar reverse($string);
$string =~ m/(\d+)oof/;
print scalar reverse("$1");
+3
source share
3 answers

What about:

$string =~ /.*foo(\d+)/;

Clarification:

$string =~ /.*     # Match any character zero or more times, greedily.
            foo    # Match 'foo'
            (\d+)  # Match and capture one or more digits.
           /x;

The miserable match of "any character" will match the first "foo" in the string, and you will stay exactly the same as the last "foo".

Example:

#!perl -w

use strict;
use 5.010;

my $string = "foo1 foo2 foo3";
$string =~ /.*foo(\d+)/;
say $1;

Conclusion:

% perl regex.pl
3
+14
source

I know that you have already chosen the answer, but I thought I would add my $ 0.02.

:

#!/usr/bin/perl

use strict;
use warnings;

my $string = "foo1 foo2 foo3 bar";
my @result = $string =~ /foo(\d+)/g;

print pop(@result) . "\n";
+4

Here's another solution, inspired by ysth's comment (if it is very long and the last foo is close to the beginning, which leads to a slow regexp): splitline in 'foo' and parse the last element for the number:

my @results = split /foo/, $string;
my ($digits) = ($results[-1] =~ m/^(\d+)/);

Again, I was always with the simplest code until it looked like the code was too long (and this was a problem in the general application), and then I would compare a number of solutions with typical inputs to see which is better.

+3
source

Source: https://habr.com/ru/post/1768325/


All Articles