首页 > 解决方案 > RegExp 用于限制 2 个小数点锡打字稿

问题描述

我在 Angular 5 应用程序的指令中有以下 RegExp:

private regex = {
        number: new RegExp(/^\d+$/),
        decimal: new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g) 
    };

在事件中,我有以下要匹配的调用:

if (next && !String(next).match(this.regex[this.numericType])) {
            event.preventDefault();
        }

我的问题是 RegExp 允许小数点后超过 2 位。我试图删除 * 并放入 {0,2} 或 {1,2} 但它不起作用。知道我应该在上面的代码中更改什么以使其在不超过 2 个小数点的情况下工作吗?

标签: regexstringtypescriptregex-lookaroundsregex-group

解决方案


你会这样做

^[0-9]+(?:\.[0-9]{0,2})?$

 ^                             # BOS
 [0-9]+                        # Required, many digits
 (?:                           # Optional group
      \. [0-9]{0,2}                 # decimal, followed by 0 - 2 digits
 )?
 $                             # EOS

推荐阅读