开发者

How can I extract digits at the end of a string using Perl?

开发者 https://www.devze.com 2022-12-17 17:21 出处:网络
I have a string of the form: \"jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425开发者_运维问答\"

I have a string of the form:

"jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   开发者_运维问答"

Toward the end it contains eight digits. There may be spaces between the digits, but there are always eight digits in the end. How do we obtain each of these digits separately using Perl?


Get input:

my $input = "jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   ";

now, extract all digits:

my @all_digits = $input =~ /(\d)/g;

Now, get the last 8 from it:

my @last_8_digits = @all_digits[-8..-1];


get rid of non-digits and then take substring from the back

$string="jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   ";
$string =~ s/[^[:digit:]]//g;
print substr ( $string ,-8);


The easiest thing to do conceptually is to apply a normalization step to the string before you extract the digits. In the example you've shown, that might be as easy as just removing all of the whitespace first. In case you need the string later, I'll do that to a copy. Once you have the normalized copy, just grab the eight digits at the end:

my $string = "jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   ";
my $copy = $string;

$copy =~ s/\s+//g; # "normalize" string

my @digits;
if( $copy =~ m/(\d{8})\z/ ) 
    {
    @digits = split //, $1
    }

print "digits are @digits\n";


/(\d\s*){8}$/

should do it. don't forget to strip out the whitespace in each of the captures.


Here's a solution that should work with any input

my $input = "dlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   ";

if  ($input =~ /((?:\d\s*){8})$/) {  # grab last 8 digits and any space

    my @nums = split /\s+|/ => $1;   # throw away space and separate each digit

    print "@nums\n";  # 2 4 4 6 1 4 2 5
}


You can use the following code

my $string="jflsdlf f fas253k46l ;sf635jsf sd;lfwio sfkljflsk-=fsd f 24461 425   ";
 my @array=split(/ / , $string);
 print "$array[$#array-1]";
 print "$array[$#array]\n";


if (m/(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*$/) {
    ($d1, $d2, $d3, $d4, $d5, $d6, $d7, $d8) = ($1, $2, $3, $4, $5, $6, $7, $8);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消