我正在寻找一个正则表达式来放入 angular 的 ng-pattern 属性。
我正在寻找一个只满足特定十进制模式的表达式,即
exactly one digit --> than a decimal --> exactly 2 digits
我想到了
\d{1}\.{1}\d{2}?
以上模式正确匹配以下数字。
2.22
3.12
0.34
这很好,但是如果用户输入 12.12
,它不会像我需要的那样拒绝它。
最佳答案
如果您只需要此内容而不需要其他内容,则应使用词首 (^
) 和词尾 ($
) anchor 。你的正则表达式是:
var regex = /^\d\.\d{2}$/; //then just bind to controller
If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in
^
and$
characters. For instance,"abc"
will be converted tonew RegExp('^abc$')
.
请注意,如果您使用字符串输入,则必须转义反斜杠以获得正确的正则表达式字符串。在这种情况下,您可以使用
<input ng-model="yourModel" ng-pattern="\\d\\.\\d{2}" >
关于javascript - 寻找正则表达式以匹配 ng-pattern 中的特定十进制格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933301/