0

I have a regex which is already used in system

/^(?![.,])(?!.*[.,]$)[0-9.,](?!.*[.,]{2}).*$/ 

I need to validate the same for accepting 15 digits. User might enter decimal or might not. I am not able to understand how to handle that condition.

I tried adding the limit like this

/^(?![.,])(?!.*[.,]$)[0-9.,](?!.*[.,]{2}).{1,15}$/ 

Can someone help me with understanding how to handle decimal and still be able to check if 15 digits are entered for max length. More than 15 digits should throw error and less should be acceptable.

3
  • Is it okay for the decimal to appear at the very beginning or very end? Should it only appear once? Commented Jan 13, 2021 at 7:06
  • It should throw error if decimal is in very first or last. Only 1 decimal should be there. Commented Jan 13, 2021 at 7:15
  • 1
    Are you saying 15 digits for max length or 15 characters in total for max length? Also, what do you mean with "Only 1 decimal", should there be only one digit after an optional decimal point/comma? Commented Jan 13, 2021 at 7:17

1 Answer 1

3

The basic answer for the requirements you are listed (max 15 digits, at most one decimal, at least one digit before and after the decimal if applicable) would be this:

^(?=(?:\d\D*){1,15}$)\d+(?:[.,]\d+)?$ 

You match the full length of the string two times: once to make sure you have at most 15 digits (with possibly non-digits interspersed), and once to make sure you have only digits, and at most one decimal point/comma.

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

2 Comments

Just so I have a better understanding, which part specifically says that you are doing two different scans of the string? Is there a reason that parentheses are needed around the first grouping: (?=...$)
(?=...) is a positive lookahead, it makes sure that the following should match, but doesn't advance the position (i.e. it is a zero-width assertion). Then the bit outside the lookahead matches from the same position again (this time normally advancing the position). See here for more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.