开发者

Need a regex to match decimal numbers without leading 0s

开发者 https://www.devze.com 2023-03-09 01:04 出处:网络
It should match 0.1, 1, .01, but not 01, 00.1, or anything with chars. I\'m trying to determine if a value开发者_如何学Python should be quoted and escaped before being put into a mysql insert stateme

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

I'm trying to determine if a value开发者_如何学Python 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)$/


Try this regex:

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消