开发者

Javascript regex for amount

开发者 https://www.devze.com 2023-04-11 06:15 出处:网络
I\'m trying to get开发者_如何学Python a regex for an amount: ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])

I'm trying to get开发者_如何学Python a regex for an amount:

ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])

What I have is:

/^\d+\.\{0,1}+\d{0,2)+$/

...obviously not working. Examples of what I'm trying to do:

123 valid

123.00 valid

12.34.5 invalid

123.000 invalid

Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.


Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:

/^\d+(\.\d{1,2})?$/

Tests:

> var re = /^\d+(\.\d{1,2})?$/
  undefined
> re.test('123')
  true
> re.test('123.00')
  true
> re.test('123.')
  false
> re.test('12.34.5')
  false
> re.test('123.000')
  false


Have you tried:

/^\d+(\.\d{1,2})?$/

The ? makes the group (\.\d{1, 2}) optional (i.e., matches 0 or 1 times).


Would something like this work?

// Check if string is currency
var isCurrency_re    = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
   return String(s).search (isCurrency_re) != -1
}
0

精彩评论

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

关注公众号