简体   繁体   中英

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

Text

At least a 1 Integer Number

Max Integer Number Length is 2

At least 1 Decimal Number

Max Decimal Number Length is 3

Accepted Scenarios

"1"

"11.1"

"11.11"

"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{1,2}

is matching one or two decimal digits (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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