Friday, June 17, 2011

Regex to match an integer/float with PHP and Javascript examples

A not so easy regex I was working with yesterday, it matches from the start of the line an integer or float.

For instance,

.23 and 0.23 matches
12. and 12.23 matches
12.asd23 will get the 12. part
asd.23 does not match
12.23.23 will get the 12.23 part

etc, etc ...

Now that I said that, here it goes:

PHP example to get the part of the string matched by the regex (using preg_match):

if (preg_match('/^(?:[\d]+|)(?:\.{1}(?:\d+)?)?/', $subject, $regs)) {
$result = $regs[0];
} else {
$result = false;
}

Javascript example:

result = subject.match(/^(?:[\d]+|)(?:\.{1}(?:\d+)?)?/g);

No comments:

Followers

About me

Santa Fe, Argentina
Programador Web, PHP, MySQL, JQuery, Administrador Linux. LAMP, Lighttpd, Nginx.