简体   繁体   English

关于数字的JavaScript正则表达式

[英]JavaScript Regular Expression About Numbers

i have a input text which is a number only text that allows decimals length 3 but its not required to be a decimal number that the dot and the decimal numbers is not required to be there , that at least to be an integer number 我有一个输入文本,这是一个只允许小数长度为3的数字文本但不要求是十进制数字,点和十进制数字不需要在那里,至少是一个整数

Text 文本

At least a 1 Integer Number 至少1个整数

Max Integer Number Length is 2 最大整数数字长度为2

At least 1 Decimal Number 至少1个十进制数

Max Decimal Number Length is 3 最大十进制数长度为3

Accepted Scenarios 接受的方案

"1" “1”

"11.1" “11.1”

"11.11" “11.11”

"11.111" “11.111”

I'm new in Regular Expression and this is as far as i can get 我是正则表达式的新手,这是我能得到的

/\d{1,2}\.{0,1}\d{0,3}/;
\d{2}d{3}\

is matching exactly two digits followed by exactly three minor d ... the final backslash might cause pattern compilation error or requests a backslash succeeding those sequence of d's. 恰好匹配两个数字后跟正好三个次要d ...最后的反斜杠可能导致模式编译错误或请求反斜杠继续这些序列的d。

\d{1,2}

is matching one or two decimal digits (0-9). 匹配一个两个十进制数字(0-9)。

\d{1,3}

is matching one, two or three decimal digits. 匹配一个,两个或三个十进制数字。

If you need to match two different sequences you need to combine them using | 如果需要匹配两个不同的序列,则需要使用|组合它们 in between: 之间:

\d{1,2}|\d{1,3}

However, this makes little sense, for the latter part is including the former. 然而,这没有多大意义,因为后者包括前者。

\d{1,2}\.\d{1,3}

is matching two digits, succeeded by a period succeeded by one to three digits. 匹配两位数,后续一位乘以一到三位数。 But if period and its succeeding digits are optional as a whole, you need to group that first before declaring this group to be optional: 但是如果句点及其后续数字作为一个整体是可选的,则需要先将其分组,然后才能将该组声明为可选:

\d{1,2}(\.\d{1,3})

is grouping the latter part while 正在对后一部分进行分组

\d{1,2}(\.\d{1,3})?

is finally declaring that group to be optional. 终于宣布该组是可选的。

If that's all to be matched in a string, you need to wrap it in anchors for matching beginning and end of string resulting in 如果要在字符串中匹配所有内容,则需要将其包装在锚点中以匹配生成的字符串的开头和结尾

^\d{1,2}(\.\d{1,3})?$

You can do it as follows if I understand you correctly: 如果我理解正确的话你可以这样做:

^\\d{1,2}(\\.\\d{1,3})?$

DEMO DEMO

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

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