1

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 i.e.

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.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
Raas Masood
  • 1,475
  • 3
  • 23
  • 61
  • You mentioned `exactly one digit --> than a decimal --> exactly 2 digits `, but you are trying to match `12.12` which has two digits before decimal ? –  Jan 21 '16 at 20:22

2 Answers2

1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • this worked . ill accept the answer in 12 minutes. kindly if you could explain what do you mean by boundary. ? – Raas Masood Jan 21 '16 at 20:09
  • I have added a regex demo that also has description of this regex. Basically `\b` (word boundary) asserts there is no word character before digit – anubhava Jan 21 '16 at 20:10
  • @RaasMasood This will still match a string like `word 1.23 otherword`. It will only match the 1.23 portion, but the input would pass the `ng-pattern` validation. If that kind of string is acceptable, then this regex is the one to use. – ryanyuyu Jan 21 '16 at 20:24
  • this regex is wrong, you will have to use ^ and $ as "boundaries" one counterexample would be 0.2.22 which would be accepted by your regex contradicting the definition – Patrick Kelleter Jan 21 '16 at 20:25
1

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}" >
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53