简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM