正则表达式验证中的十进制或数值 [英] Decimal or numeric values in regular expression validation

查看:33
本文介绍了正则表达式验证中的十进制或数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式验证来仅检查十进制值或数值.但是用户输入的数值,不是第一个数字0"

I am trying to use a regular expression validation to check for only decimal values or numeric values. But user enters numeric value, it don't be first digit "0"

我该怎么做?

推荐答案

1-9 范围内的数字后跟零个或多个其他数字:

A digit in the range 1-9 followed by zero or more other digits:

^[1-9]\d*$

允许带有可选小数点后跟数字的数字.1-9 范围内的数字后跟零个或多个其他数字,然后可选地后跟小数点后跟至少 1 位数字:

To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:

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

注意事项:

  • ^$ 锚定开始和结束基本上是说整个字符串必须匹配模式

  • The ^ and $ anchor to the start and end basically saying that the whole string must match the pattern

()? 匹配括号内的整个事物的 0 或 1

()? matches 0 or 1 of the whole thing between the brackets

更新以处理逗号:

在正则表达式中 . 有一个特殊的含义——匹配任何单个字符.要逐字匹配字符串中的 .,您需要使用 \. 转义 . 这就是上面正则表达式中的 \. .因此,如果您想使用逗号,则模式很简单:

In regular expressions . has a special meaning - match any single character. To match literally a . in a string you need to escape the . using \. This is the meaning of the \. in the regexp above. So if you want to use comma instead the pattern is simply:

^[1-9]\d*(,\d+)?$

进一步更新以处理逗号和句号

如果您想在数字组之间允许 . 和在整数部分和小数部分之间允许 , ,请尝试:

If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:

^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$

即这是一个 1-9 范围内的数字,后跟最多 2 个其他数字,然后是零组或多组句号,后跟 3 位数字,然后是可选的逗号和数字.

i.e. this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.

如果您想在数字之间的任何位置允许 . ,请尝试:

If you want to allow a . anywhere between the digits then try:

^[1-9][\.\d]*(,\d+)?$

即数字 1-9 后跟零个或多个数字或句号,可选后跟逗号和一个或多个数字.

i.e. a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.

这篇关于正则表达式验证中的十进制或数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆