Js中十进制格式的正则表达式(123,456.789和123.456,789)

时间:2016-11-07 18:57:00

标签: javascript regex

我需要这个十进制格式的2的输入模式的正则表达式:

123,456.789123.456,789

DECIMAL_COMMA_REGEXP: new RegExp('^[+-]?(?=.)(?:\\d+\\.)?\\d+(?:,\\d+)?$')
DECIMAL_POINT_REGEXP: new RegExp('^[+-]?(?=.)(?:\\d+,)?\\d+(?:\\.\\d+)?$')

如果我提供此输入:1.000.000,123不接受它。为什么以及定义正则表达式的原因是什么?

1 个答案:

答案 0 :(得分:1)

这两个应该这样做:

DECIMAL_COMMA_REGEXP: new RegExp('^[+-]?\\d{1,3}(\\.\\d{3})*(,\\d+)?$')
DECIMAL_POINT_REGEXP: new RegExp('^[+-]?\\d{1,3}(,\\d{3})*(\\.\\d+)?$')

工作示例:

a = '123,456.789'
b = '123.456,789'
c = '1.11111'
d = '12.21'
e = '1,11111'
f = '12,21'
g = '12345.1'
h = '12345,1'

DECIMAL_COMMA_REGEXP = new RegExp('^[+-]?\\d{1,3}(\\.\\d{3})*(,\\d+)?$')
DECIMAL_POINT_REGEXP = new RegExp('^[+-]?\\d{1,3}(,\\d{3})*(\\.\\d+)?$')

console.log('COMMA TESTS:')
console.log(a, DECIMAL_COMMA_REGEXP.test(a))
console.log(b, DECIMAL_COMMA_REGEXP.test(b))
console.log(c, DECIMAL_COMMA_REGEXP.test(c))
console.log(d, DECIMAL_COMMA_REGEXP.test(d))
console.log(e, DECIMAL_COMMA_REGEXP.test(e))
console.log(f, DECIMAL_COMMA_REGEXP.test(f))
console.log(g, DECIMAL_COMMA_REGEXP.test(g))
console.log(h, DECIMAL_COMMA_REGEXP.test(h))

console.log('')

console.log('POINT TESTS:')
console.log(a, DECIMAL_POINT_REGEXP.test(a))
console.log(b, DECIMAL_POINT_REGEXP.test(b))
console.log(c, DECIMAL_POINT_REGEXP.test(c))
console.log(d, DECIMAL_POINT_REGEXP.test(d))
console.log(e, DECIMAL_POINT_REGEXP.test(e))
console.log(f, DECIMAL_POINT_REGEXP.test(f))
console.log(g, DECIMAL_POINT_REGEXP.test(g))
console.log(h, DECIMAL_POINT_REGEXP.test(h))

这些工作的方式是:

  1. 任何数字1至3次(1 10 100)
  2. 与(1)相同,但前面有,。零次或多次(,999,999 ...)
  3. 任意数量的十进制数字或无(.123456)
  4. 逗号小数:https://regex101.com/r/PnfUiL/1 点小数:https://regex101.com/r/PnfUiL/2