简体   繁体   中英

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.

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.

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

According to the ng-pattern documentation

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 to new RegExp('^abc$') .

Note that if you use a string input, you'll have to escape the backslashes to get the proper regex string. In this case you could just use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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