Reputation: 4124
I created this regular expression:
^$|^[1-9]+([\.,]\d{0,2})?$
It should accept:
1
11,00
100,88 (error)
100 (error)
11.00
100.88
Shouldn't accept:
0
-5
0,55
0.55
How can I fix it?
Upvotes: 1
Views: 120
Reputation: 1492
From my reading of your question you want the string "(error)" to be a valid suffix. Is that right? If so:
^$|^[1-9]+[0-9]*([\.,]\d{0,2})?( \(error\))?$
Upvotes: 0
Reputation: 2226
So long as the first character is a digit between 1
and 9
, subsequent characters can be any digit. However, your expression excludes subsequent 0
's; you need to allow for there to be any number of digits so long as the first character is between 1
and 9
:
^$|^[1-9]\d*([\.,]\d{0,2})?$
^
the beginning of the string[1-9]
any digit except "0"
\d*
any digit between 0 and unlimited times([\.,]\d{0,2})?
"."
or ","
followed by between zero and 2 digits$
end of stringSee this example for further explanation and unit tests.
Upvotes: 1
Reputation: 626853
You can enclose the whole pattern with an optional group and use a \d
instead of the [1-9]
and add a (?!0+)
negative lookahead restriction to exclude matching values with leading zeros:
^(?!0+)(?:\d+(?:[.,]\d{0,2})?)?$
^^^^^^^^^ ^^
See the regex demo
If you do not want to match 53.
-like values, you need to replace {0,2}
with {1,2}
.
Pattern details:
^
- start of string(?!0+)
- no zeros at the beginning(?:\d+(?:[.,]\d{0,2})?)?
- optional (one or zero) sequence of:
\d+
- 1 or more digits(?:[.,]\d{0,2})?
- optional (one or zero) sequence of:
[.,]
- either a .
or ,
\d{0,2}
- two, one or zero digits$
- end of string.Upvotes: 2