punch_card_don has asked for the wisdom of the Perl Monks concerning the following question:

Mondo Monks,

I have a collection of strings of the general form:

abunchofalphanumericcharacters_somenumbers

That is, a bunch of whatever that may contain letters, numbers, undescors, dashes and what have you, then a final series of numbers. Two examples:

asdf_sadf-3i897sdyf33987
3w45t-wevt453_838475693

I want to capture the final string of numbers after the last non-numerical character, in these cases 33987 and 838475693. Note that the last non-numerical character may be a letter (a-z, either case) or an undescor or a dash, or any number of other non-whitespace characters. The strings contain no whitespace.

But how?

Thanks.

  • Comment on Regex: find all trailing numerical digits in a string

Replies are listed 'Best First'.
Re: Regex: find all trailing numerical digits in a string
by dragonchild (Archbishop) on Dec 06, 2004 at 17:42 UTC
    What have you tried? How would /(\d+)$/ not work?

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Re: Regex: find all trailing numerical digits in a string
by VSarkiss (Monsignor) on Dec 06, 2004 at 17:58 UTC

      Well you really don't even need parens if you can live with $& or substr( $str, $-[0], $+[0] - $-[0] ) . . . </nit> :)

        It would seem to me that $& would be more readable than substr( $str, $-[0], $+[0] - $-[0] ).

        use strict; while(<DATA>) { chomp; /\d+$/; print "Numeric: [$&]\n"; } __DATA__ asdf_sadf-3i897sdyf33987 3w45t-wevt453_838475693

        Is there a case where you would use the substr over $&?


        "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.


        OSUnderdog
Re: Regex: find all trailing numerical digits in a string
by punch_card_don (Curate) on Dec 06, 2004 at 18:25 UTC
    Ya, that's it. I'm terrible at regex's to begin with, made worse by being burned out from a week of 12 hour days. Just a few more days and I can rest.....