Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Reg Ex exercise

by Athanasius (Abbot)
on Dec 05, 2012 at 16:28 UTC ( #1007325=note: print w/ replies, xml ) Need Help??


in reply to Reg Ex exercise

#! perl use Modern::Perl; while (<DATA>) { chomp; if (/ ^ (?: (?: -? \d+) | (?: -? \d+ \. \d+)) $ /x) { say 'Yes, ', $_, ' is a number'; } else { say 'No, ', $_, ' is not a number'; } } __DATA__ 4 -7 0.656 -67.35555 5. 56F .32 -.04

Output:

2:17 >perl 417_SoPW.pl Yes, 4 is a number Yes, -7 is a number Yes, 0.656 is a number Yes, -67.35555 is a number No, 5. is not a number No, 56F is not a number No, .32 is not a number No, -.04 is not a number 2:17 >

Some notes:

  • | is bitwise-OR outside a regex, and alternation in a regex. For logical OR, use || (or or).

  • Within a regex, a dot matches any character. To match the decimal point, you need to escape it: “\.”.

  • Prefer chomp to chop — the former removes a line-termination if present, the latter removes the last character regardless.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


Comment on Re: Reg Ex exercise
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (16)
As of 2015-07-01 17:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (12 votes), past polls