b.d
b.d

Reputation: 53

Regular expression to accept numbers up to 5 digits and decimals

\d{0,5}\.\d{0,6} Does not accept numbers without a decimal. How do i get it to ignore the decimal place when not entered

Upvotes: 1

Views: 4958

Answers (2)

ajit-jain
ajit-jain

Reputation: 236

/(\d{0,5})(\.\d{0,5})*/ you can also use this

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

Make the entire decimal group optional:

\d{0,5}(?:\.\d{0,6})?

This would match 0 to 5 digits, with or without a decimal point followed by another 0 to 6 digits.

We can add ?: inside a capture group to tell the regex engine not to capture what is inside the parentheses. In this case, without using ?: the engine would have captured the optional decimal point and subsequent digits. Turning off capture could improve performance of the regex, which is why you will see this being discussed often with regex questions on Stack Overflow.

Upvotes: 4

Related Questions