regular expression

ignoRamous
ignoRamous used Ask the Experts™
on
Need help on what regular expression to use in order to check if the number is valid?
Example of valid #: 10, 1.5, 2.51, -1, -.1
but not this kind of #: 2.1.2, -1.24.1
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Let's try to say what you're looking for in words:

A valid number has:

a) an optional - sign at the beginning
b) followed by zero or more digits
c) followed by an optional decimal point
d) followed by zero or more digits

with the proviso that there must be at least one digit before or after the decimal point.

The best way I could think of to do this was this regular expression:

print 'valid' if $number =~ /^-?\d*(\d\.|\.\d)\d*$/;

The ^ and $ anchors are needed to ensure that the entire string is matched by the entire pattern.

Have you just suckered me into doing your homework for you?

ozo
Most Valuable Expert 2014
Top Expert 2015

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

Author

Commented:
$word =~ s/[,.?!"-]//

Is this correct if the word contain either one of these .,?!-" I will subtitute to nothing
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Re: $word =~ s/[,.?!"-]//;

Yes. The first occurrence of one of the characters specified in the [...] class will be replaced by nothing, thus removing it from the string.

Author

Commented:
How would you delete the punctuation at the end if the word contains .,?...
For example, Oh! or What?
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
s/\b[.?!]//g

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial