如何将 preg_match 用于 - , + , .价值观?
我使用此 preg_match
条件来匹配正值、负值和小数值
/^[0-9,-\.]{1,50}$/
但是当我输入 --34.000 时它不会显示错误,当我输入 34...9868 时它不会显示错误, 我想要的是它必须只接受正值、负值和小数。
I use this preg_match
condition for matching positive, negative and decimal values
/^[0-9,-\.]{1,50}$/
But when I enter --34.000 it does not show error, when I enter 34...9868 it does not show error,
what I want is that it must accept only positive, negative and decimal values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要检查它是否是数字,最好使用诸如
is_numeric()
之类的东西。你的正则表达式完全坏了,因为现在它甚至只能接受包含 50 个点的字符串
Better if you use something like
is_numeric()
if yuo need to check if it's a number.And your regex is totally broke because as now it can accept even only a string containing 50 dots
正如 yes123 所说,有更好的方法来检测给定的输入字符串是否是数值。如果您想坚持使用正则表达式,以下内容可能适合您:
解释:
^
)- 匹配
字符 (-?
);?
表示“不需要”[0-9]+
)(?:. ..)?
);?:
表示“不捕获子模式”\.
);.
由于其特殊功能需要转义[0-9]+
)$)
As yes123 stated, there are better ways to detect if a given input string is a numeric value. If you'd like to stick to regular expressions, the following might be OK for you:
Explanation:
^
)-
character (-?
); the?
means "not required"[0-9]+
)(?:...)?
);?:
means "do not capture the subpattern"\.
); the.
needs to be escaped due to its special function[0-9]+
)$
)您需要拆分正则表达式,以便它只接受正确位置的字符。例如:
解释此表达式:
[+\-]?
:这会检查数字的 + 或 - 前缀。它完全是可选的,但只能是+或-。([0-9]+,)*
:这允许一组可选的逗号分隔数字。这是针对数千、数百万等。[0-9]+
:这要求该值至少包含一些数字(\.[0-9]+)?
:最后,这允许带有尾随数字的可选小数点。You need to split up your regular expression so that it only accepts the characters in the right places. For example:
To explain this expression:
[+\-]?
: This checks for a + or - prefix to the number. It's completely optional, but can only be a + or -.([0-9]+,)*
: This allows an optional set of comma-delimited numbers. This is for the thousands, millions etc.[0-9]+
: This requires that the value contains at least some numbers(\.[0-9]+)?
: Finally, this allows an optional decimal point with trailing numbers.尝试这个正则表达式
^-?\d*\.?\d+$
但我想它不能限制为 50 个字符
try this regex
^-?\d*\.?\d+$
i suppose it however cannot be limited to 50 chars