Home > Mobile >  PERL How to match last n digits of a string with n consecutive digits or more?
PERL How to match last n digits of a string with n consecutive digits or more?

Time:12-06

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?

CodePudding user response:

/([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/

CodePudding user response:

Whenever you want to match something at the end of a string, use the end of line anchor $.

$content =~ m/(\d{11})$/;

If that pattern is not the very end, but you want to match the "last" occurence of that pattern, you would first match "the entire string" with /.*/ and then backtrack to the final occurence of the pattern. The /s flag permits the . metacharacter to match a line feed.

$content =~ m/.*(\d{11})/s;

See the Perl regexp tutorial for more information.

  • Related