regex - JavaScript regular expression match amount -



regex - JavaScript regular expression match amount -

i'm trying write regular look match amounts. in case, need either amount should positive integer or if decimal used, must followed 1 or 2 integers. basically, next valid amounts:

34000 345.5 876.45

what wrote this: /[0-9]+(\.[0-9]{1,2}){0,1}/

my thinking using parenthesis so: (\.[0-9]{1,2}), able bundle whole "decimal plus 1 or 2 integers" part. isn't happening. among other problems, regex allowing stuff 245. , 345.567 slip through. :(

help, please!

your regular look good, need match origin , end of string. otherwise, regex can match portion of string , still (correctly) homecoming match. match origin of string, utilize ^, end, utilize $.

update: avinash has noted, can replace {0,1} ?. js supports \d digits, regex can farther simplified

finally, since if testing against regex, can utilize non-capturing grouping ( (?:...) instead of (...)), offers better performance.

original: class="snippet-code-js lang-js prettyprint-override">/[0-9]+(\.[0-9]{1,2}){0,1}/.test('345.567')

fixed, , faster ;)

class="snippet-code-js lang-js prettyprint-override"> /^\d+(?:\.\d{1,2})?$/.test('345.567')

javascript regex

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -