0

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}/;
1
  • Honestly, regex are something you have to study from the ground up. Your assignment looks pretty challenging. It is a school assignment, right? Take some time at regular-expressions.info/tutorial.html and you won't regret it. You can't be a serious programmer without regex in your toolbox. Commented Apr 27, 2014 at 8:33

2 Answers 2

1

You can do it as follows if I understand you correctly:

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

DEMO

Sign up to request clarification or add additional context in comments.

10 Comments

your ans is the most perfect but i need 1 more thing that not to allow the . if there is no numbers after it and thank you very much for helping me
@Marwan, Yes that is what it does.
mmm i dont know does i write it right var d = /^\d{1,2}(\.\d{1,3})?$/mg; d.test(11.);
i need to allow the . only if i have at least one decimal num after it
@Marwan, Wait, so 11. is allowed or not?
|
1
\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})?$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.