Parris Varney
Parris Varney

Reputation: 11478

Need a regex to match decimal numbers without leading 0s

It should match 0.1, 1, .01, but not 01, 00.1, or anything with chars.

I'm trying to determine if a value should be quoted and escaped before being put into a mysql insert statement. I have to watch out for some varchar keys that could be numeric with leading 0s that would be truncated if inserted as a number.

I'd also use a built in php or mysql function, if available.

EDIT: This one seems to cover all my bases:

/^([1-9][0-9]*(\.[0-9]+)?|0\.[0-9]+|\.[0-9]+|0)$/

Upvotes: 2

Views: 1385

Answers (3)

morja
morja

Reputation: 8550

Try this:

(?:^|\s|,)((?:(?:[1-9]\d*|0)(?:\.\d+)?)|(?:\.\d+))(?:$|\s|,)

See here.

Or

^((?:(?:[1-9]\d*|0)(?:\.\d+)?)|(?:\.\d+))$

if they appear each in a single line. See here.

Upvotes: 1

Keith
Keith

Reputation: 5381

Try this regex:

([1-9]\d*(\.\d+)?)|(0?\.\d+)

Upvotes: 2

mario
mario

Reputation: 145482

This would suit your examples:

preg_match('#^(?=[1-9]|0\.|\.\d)\d*(\.\d+)?$#', $num)

The ?= assertion ensures that it either starts with 1-9 or 0., so any other leading zeros are excluded. You might want to limit the amount of decmals \d+ can match though.

Upvotes: 1

Related Questions