regex - 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 个小数点的情况下工作吗?
解决方案
你会这样做
^[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
推荐阅读
- java - Java:在 JTextArea 中未正确显示 UTF8 编码
- windows - sklearn:ImportError:DLL加载失败:找不到指定的模块
- python - ansible 测试失败,因为 lookup('file', '/path/to/file') 在 gitlab-ci 中返回旧内容
- objective-c - macOS/iOS PDFKit:创建文档的大纲根
- javascript - 如何将 PyTest 配置为读取 .toml 而不是 .conf?
- angular - Angular Material 2 Reactive Forms -- mat-error with *ngIf 在验证 minLength、电子邮件和所需的验证工作时未显示
- sql-server - 执行简单 SQL Server 存储过程时出错“转换 varchar 值时失败”
- mysql - 我是否需要在“IN (SELECT MAX(id)”子查询中重复 WHERE 子句?
- azure - 从 USQL 中的元数据动态生成提取脚本
- r - 如何在 R 的 FTP 服务器上连接到 SQLite?