Perl: How to match last n digits of a string with n consecutive digits or more?

0

Issue

I use the following:

if ($content =~ /([0-9]{11})/) {
    my $digits = $1;
}

to extract 11 consecutive digits from a string. However, it grabs the first 11 consecutive digits. How can I get it to extract the last 11 consecutive digits so that I would get 24555199361 from a string with hdjf95724555199361?

Solution

/([0-9]{11})/

means

/^.*?([0-9]{11})/s   # Minimal lead that allows a match.

You get what you want by making the .* greedy.

/^.*([0-9]{11})/s    # Maximal lead that allows a match.

If the digits appear at the very end of the string, you can also use the following:

/([0-9]{11})\z/

Answered By – ikegami

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More