简体   繁体   English

实数的 ng-pattern 正则表达式

[英]ng-pattern regular expression for real number

This is more a question for my own curiosity.这更多是出于我自己的好奇心的问题。 I have a working solution, but I'm curious if anybody has any insight as to why one solution works and the other does not.我有一个可行的解决方案,但我很好奇是否有人对为什么一个解决方案有效而另一个没有任何见解有任何见解。

I needed a regular expression to validate a user has entered a valid number.我需要一个正则表达式来验证用户输入的有效数字。 Some examples:一些例子:

87 87

887.65 887.65

-87 -87

-87.65 -87.65

My first attempt looked like this:我的第一次尝试是这样的:

^(\-?[0-9]+(\.[0-9]*)?)$

It worked great except strings like '7x', '1a', '89p' were accepted.除了接受像“7x”、“1a”、“89p”这样的字符串外,它工作得很好。 My new solution is below, and it seems to work just fine:我的新解决方案如下,它似乎工作得很好:

^(\-?[0-9]+(\.[0-9]+)?)$

The second one (note the '+') is slightly more concise, but I fail to see why the first one accepted letters and the second one doesn't.第二个(注意“+”)稍微简洁一些,但我不明白为什么第一个接受字母而第二个不接受。 Does anybody see what I'm missing?有人看到我错过了什么吗?

The "."这 ”。” in your regex is for the character "."在您的正则表达式中用于字符“。” literally, so it should be escaped "\\.", otherwise it will match any character.从字面上看,所以它应该被转义为“\\.”,否则它将匹配任何字符。 In the second regex the "+" operator demands at least one decimal so it wont match "7x", but it will match "7x1", see this Regex demo在第二个正则表达式中,“+”运算符需要至少一位小数,因此它不会匹配“7x”,但会匹配“7x1”,请参阅此正则表达式演示

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

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