Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Extract last two digits from numbers

by yosefm (Friar)
on Jan 06, 2004 at 10:13 UTC ( #319064=note: print w/ replies, xml ) Need Help??


in reply to Extract last two digits from numbers

Assuming the number is at the end of the variable being matched, use: /\d{2}$/. the '\d' means match digits, the '{2}' means two exactly, and the '$' means end of line. Other option: /\d\d$/ (simpler).

Update: Note that L~R's regex is more specific (putting '^' first means start of line) while tachyon's regex is more relaxed, finding any 4 digit number and capturing its last two digits (using parentheses).

Another update: See L~R's reply below.


Comment on Re: Extract last two digits from numbers
Re: (2) Extract last two digits from numbers
by Limbic~Region (Chancellor) on Jan 06, 2004 at 10:23 UTC
    yosefm,
    finding any 4 digit number and capturing its last two digits

    Just to be clear, tachyon's regex will match the last two digits of the first set of digits in a string that are at least 4 digits long

  • "The cat 1234567 in the hat"
  • 1234
  • "Just like 3456789 he was 12345"

    Cheers - L~R

    Update: As duff points out below, I am an idiot. My above statement would be correct if the regex had been /\d\d(\d\d)\b/

      Just to be clear, tachyon's regex will match the last two digits of the first set of digits in a string that are at least 4 digits long

      That's not clear at all because that's not what his regular expression does. What it does is match the second pair of the first sequence of 4 digits within a string. Here's tachyon's code again: my ($digits)= $str =~ m/\d\d(\d\d)/; and here is what your examples should have looked like:

      • "The cat 1234567 in the hat"
      • 1234
      • "Just lie 3456789 he was 12345"

        duff,
        That's what I get for trying to type what my brain is thinking after spending nearly 36 hours traveling half way around the world with only a few hours sleep. You are most correct. I was thinking about modifying my ^ and $ anchors to \b and somehow saw them in tachyon's code. They are obviously not there and I obviously need more sleep.

        Salamat po (courteous form of thank you in Tagalog)

        L~R

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://319064]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2014-08-29 10:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (280 votes), past polls