Reputation:
I am trying to validate a text field that accepts number like 10.99, 1.99, 1, 10, 21.
\d{0,2}\.\d{1,2}
Above expression is only passing values such as 10.99, 11.99,1.99, but I want something that would satisfy my requirement.
Upvotes: 0
Views: 7563
Reputation: 103774
I think patterns of this type are best handled with alteration:
/^\s*([-+]?[0-9]*\.[0-9]+([eE][-+]?[0-9]+)?)$ #float
| # or
^(\d{1,2})$ # 2 digit int/mx
Upvotes: 0
Reputation: 424993
Assuming you don't want to allow edge cases like 00
, and want at least 1 and at most 2 decimal places after the point mark:
^(?!00)\d\d?(\.\d\d?)?$
This precludes a required digit before the decimal point, ie ".12"
would not match (you would have to enter "0.12"
, which is best practice).
If you're using String#matches()
, you can drop the leading/trailing ^
and $
, because that method must to match the entire string to return true
.
Upvotes: 1
Reputation: 59960
Can you try using this :
(\d{1,2}\.\d{1,2})|(\d{1,2})
Here is a Demo, you can check also simple program
You have two parts or two groups one to check the float numbers #.#, #.##, ##.##, ##.#
and the second group to check the integer #, ##
, so we can use the or |
, float|integer
Upvotes: 0
Reputation: 41
Try this:
^\d{1,2}(\.\d{1,2})?$
^
- Match the start of string \d{1,2}
- Must contains at least 1 digit at most 2 digits (\.\d{1,2})
- When decimal points occur must have a . with at least 1 and at most 2 digits ?
- can have zero to 1 times $
- Match the end of stringUpvotes: 3
Reputation: 3894
First \d{0,2} does not seem to fit your requirement as in that case it will be valid for no number as well. It will give you the correct output but logically it does not mean to check no number in your string so you can change it to \d{1,2}
Now, in regex ? is for making things optional, you can use it with individual expression like below:
\d{1,2}\.?\d{0,2}
or you can use it on the combined expression like below
\d{1,2}(\.\d{1,2})?
You can also refer below list for further queries:
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(abc|def) Matches abc or def
Useful link : https://regexone.com/
Upvotes: 1