简体   繁体   English

寻找正则表达式以匹配ng-pattern中的特定十进制格式

[英]looking for a regular expression to match specific decimal format in ng-pattern

i am looking for a regular expression to put in ng-pattern attribute of angular. 我正在寻找一个正则表达式来放置ng的ng-pattern属性。

i am looking for an expression that satisfies only a specific decimal pattern ie 我正在寻找只满足特定十进制模式的表达式,即

exactly one digit --> than a decimal --> exactly 2 digits 

i came up with 我想出了

\d{1}\.{1}\d{2}?

The above pattern matches the following numbers correctly. 上面的模式正确匹配以下数字。

2.22
3.12
0.34

which is fine but if user enters 12.12 it doesn't reject this as I need it to. 很好,但是如果用户输入12.12它不会拒绝我所需要的。

exactly one digit --> than a decimal --> exactly 2 digits 正好一位--比十进制->正好两位

Use word boundaries to prevent it to match unwanted text on either side: 使用单词边界来防止它与任一侧的不需要的文本匹配:

\b\d\.\d{2}\b

RegEx Demo 正则演示

If you want precisely this content and nothing else, you should use the start of word ( ^ ) and end of word ( $ ) anchors. 如果您只需要此内容,而没有其他内容,则应使用单词的开头( ^ )和单词的结尾( $ )锚点。 Your regex would be: 您的正则表达式为:

var regex = /^\d\.\d{2}$/;         //then just bind to controller

Tested on regex101 在regex101上测试

According to the ng-pattern documentation 根据ng-pattern文档

If the expression evaluates to a RegExp object, then this is used directly. 如果表达式的计算结果为RegExp对象,则可以直接使用该表达式。 If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. 如果表达式的计算结果为字符串,则将其用^$字符包装后将转换为RegExp。 For instance, "abc" will be converted to new RegExp('^abc$') . 例如, "abc"将被转换为new RegExp('^abc$')

Note that if you use a string input, you'll have to escape the backslashes to get the proper regex string. 请注意,如果使用字符串输入,则必须转义反斜杠以获取正确的regex字符串。 In this case you could just use 在这种情况下,您可以使用

<input ng-model="yourModel" ng-pattern="\\d\\.\\d{2}" >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM