Perl - Return last alpha character after last digit in a string and return modified string too

perl, regex

Solution

Using `\pL` will avoid capturing numbers, and making the string optional will assure that the match happens even for numbers without ending letters.

my $var = '123456d';
my ($num, $letter) = $var =~ /^(\d+)(\pL)?$/;

Note that you cannot use `\w` to capture the possible ending letter, because it also includes numbers. As tchrist has pointed out, `\p{alpha}` can also be used.

Problem

I have a string like this: ``` $var = '123456d'; ``` or possibly ``` $var = '123456'; # (no alpha char) ``` There will be up to 6 digits no less than 5 if that matters. No alpha, spaces or special mixed in the numbers. In my Perl script, I need to remove and return the last alpha character AND the string without the alpha character. I suppose can use \D and trim? or chop? but, there must be an easy way to get both vars quickly. ``` my $numbers =~ s/\D+?$var//; #??? my $alpha = substr($var, 0, -1); ## but no alpha check. ``` or ``` my $alpha = chop($var); ## but no alpha check. ``` then if a-Z and so on to check if it is an alpha character. Or the limit of my ability solution: ``` $alpha = $var; $alpha =~ s/[0-9]//ig; $var =~ s/[a-Z]//ig; $numbers = $var; ``` so result: ``` ($numbers == '123456') ($alpha eq 'd') (or '' if nothing) ``` I feel like this is too trivial to ask here but, I just cannot find or write an applicable solution. My use of =~ s is just a guess but, there must be a better way or even a one liner. Thanks for all the help here... SORRY after thought! There may be 2 alpha characters after the digits! They would need to be returned together as a single var ($alpha eq 'dd') I found this too to0: ``` $var =~ s{^([0-9]+).*}{$1}i; ```

Original source