0

I am totally new to creating my own regular expressions. I have one reg ex developed my team member as listed below

  ^\s*-?\d{1,3}(\.\d{1,4})?\s*$

This will ensure that the value entered is having a maximum of 3 digits and may or may not have a negative sign.

RegExp Calculator

If I test with a value, “-1000” it will say the entered value does not meet the requirements and an error will be shown to the user.

I need to modify the expression in such way that:

If a “-“ sign is there, it can have more than 3 digits and decimals. [But if the user enter a “-“ and any alphabets, it should not match ]

3 Answers 3

1

You could change it to this one :

^\s*(\d{1,3}|-\d+)(\.\d{1,4})?\s*$

The first part in the form (a|b) means a or b. It means that the part before the comma is either

  • 1 to 3 digits
  • or - followed by at least one digit
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Can you please explain why you modified the below one? ^\s*(\d{1,3}|-\d{1,})(\.\d{1,4})?\s*$
I just thought that \d+ was cleaner than \d{1,}. It's the same.
1

Use |(OR) operator in regex

^(\d{1,3}([.]\d{1,4})?|-\d+([.]\d+)?)$

Comments

-1

If you just want to validate if a number is between -999 and 999 please parse it to an Integer and check -999 < x < 999.

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.