简体   繁体   English

如何在正则表达式中仅允许3位数字和一个点

[英]How to allow only 3 digit and one dot in Regular Expression

I want to do like this : 3.40 and not more than 3 characters and one dot: 我想这样做:3.40,且不超过3个字符和一个点:

<md-input-container class="md-block">
                    <label>Marks/CGPA</label>
                    <input type="text" name="education.cgpa" ng-model="education.cgpa"
                           ng-pattern="/^[0-9]{0,4}$/">
                    <div class="input-validation" ng-show="educationSaveForValidate['education.cgpa'].$error.pattern">
                        Insert valid CGPA
                    </div>
                </md-input-container>

How can I allow only 3 digits and one dot in Regular Expression? 如何在正则表达式中仅允许3位数字和一个点?

You may use a single regex like 您可以使用单个正则表达式

ng-pattern="/^(?!.{5})\d*\.?\d+$/"

or - to allow an empty string: 或-允许使用空字符串:

ng-pattern="/^(?!.{5})\d*\.?\d*$/"

You may also move the length check out of the regex: 您也可以将长度检查移出正则表达式:

ng-pattern="/^\d*\.\d*$/" ng-maxlength="4"

Details 细节

  • ^ - start of string ^ -字符串开头
  • (?!.{5}) - a negative lookahead that fails the match if there are any 5 chars in the input string (?!.{5}) -如果输入字符串中有5个字符,则匹配失败的否定超前
  • \\d* - 0+ digits \\d* -0+个数字
  • \\.? - an optional . -可选的.
  • \\d* - zero or more digits (if \\d+ is used, then 1 or more digits) \\d* -零个或多个数字(如果使用\\d+则为1个或多个数字)
  • $ - end of string. $ -字符串结尾。

To disallow any leading/trailing spaces, add ng-trim="false" . 要禁止任何前导/尾随空格,请添加ng-trim="false"

https://regex101.com/r/kF0hJ5/17 https://regex101.com/r/kF0hJ5/17

Check this link above, I hope it'll help you. 检查上面的此链接,希望对您有所帮助。 Sorry for commenting link here. 很抱歉在这里评论链接。 Doing so as I have less repo. 这样做是因为我的回购减少了。

我已经用这种方式解决了我的问题……

ng-pattern="/^\d\.\d{0,2}$/"

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

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