javascript - RegEx to match only numbers incorrectly matching -


i'm trying use regular expression in javascript match number or number containing decimal. regular expression looks [0-9]+ | [0-9]* \. [0-9]+.

however, reason '1a'.match(/^[0-9]+|[0-9]*\.[0-9]+$/) incorrectly finds match. i'm not sure part of expression matching a.

the problem alternation. says:

  ^[0-9]+           # match integer @ start |                   # or   [0-9]*\.[0-9]+$   # match decimal number @ end 

so first alternative matches.

you need group alternation:

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

the ?: optimisation , habit. suppresses capturing not needed in given case.

you away without alternation well, though:

/^[0-9]*\.?[0-9]+$/ 

or shorter:

/^\d*\.?\d+$/ 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -