newbie regular expression question

J

John

I would like to know which regular expression will match a number with
decimals between 0 and 1.



I have tried and fail with:


/\d/ #match any number
\/[0-1]?\.?[0-9]*/ # match any number
/[0-1]||(0\.[0-9]+)/ # match also 0.24.0220

note the number can be expressed as 0.28, 0.03455, .0123432 but never
with [+-] symbols.

Any help


Cheers
J
 
A

A. Sinan Unur

(e-mail address removed) (John) wrote in
I would like to know which regular expression will match a number with
decimals between 0 and 1.

perldoc -q " How do I determine whether a scalar is a
number/whole/integer/float?"

The line above will be wrapped by my newsreader ... instead enter it as one
long line.
 
B

Ben Liddicott

Hi John,

\d matches any single digit. To match a number, you need \d+.

m/
\d* # match optional leading digits
\. # decimal point
\d+ # digits following the decimal
/x # allow embedded comments and whitespace

If the numbers following the decimal are optional (i.e., 123 is allowed) this will do the trick:

m/
\d* # match optional leading digits
(?: # either
(?: # this group:
\. # decimal point
\d+ # digits following the decimal
) # end group
| # or
(?<\d) # preceeding digit exists... presumably matched by \d* above
) # end either/or group
/x # allow embedded comments and whitespace


If you need to match "123." as well... well, I have given you a starting point.

Oh, and
perldoc perlre
perldoc perlrequick
perldoc perlretut

obviously.

Cheers,
Ben Liddicott
 
G

Glenn Jackman

John said:
I would like to know which regular expression will match a number with
decimals between 0 and 1.

Why use a regex for this?
do_something() if (0 <= $n and $n <= 1)

However
my $re = qr{^(?:(?:[01](?:\.0*)?)|(?:0?\.\d+))$};
do_something() if $n =~ /$re/;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top