Mamta
Mamta

Reputation: 921

Regex issue for decimal field - Swift

I am trying to implement a regex for decimal numbers such that it allows:

I have tried this: static let decimalRegex = try! NSRegularExpression(pattern: "^(?!(0))\\d{0,10}(\\.$|\\.\\d{0,2}$|$)", options: [])

It does not let me type in 0 so to denote 0.01 I enter .01 in the textfield. When I re-populate the same in the textfield on edit, it shows as 0.01 but i am unable to delete/edit/insert anything in it.

Please help so that all the conditions above can be met through regex.

Upvotes: 2

Views: 1126

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

I suggest using

"^(?![0.]+$)[0-9]{0,10}(?:\\.[0-9]{0,2})?$"

See the regex demo

Details

  • ^ - start of string
  • (?![0.]+$) - up to the end of string, there can't be only zeros and/or dots
  • [0-9]{0,10} - zero to ten digits
  • (?:\\.[0-9]{0,2})? - an optional sequence of
    • \\. - a dot
    • [0-9]{0,2} - zero or two digits
  • $ - end of string.

Upvotes: 3

Damo
Damo

Reputation: 6433

Building on the answer by @Wiktor have you thought about other edge cases

the regex ^(?![.0]+$)[0-9]{0,10}(\.[0-9]{0,2})?$ try it here

will match:

1
1.
1.12
01
0123456789
1234567890.12
0000000001
012.00
0.01
.01

but will not match:

0
-0
-0.0
0.0
1.123
12345678900
01234567890
1.000
1.001
1.1.
.1.1
-123
-0123.45
-0.01

Upvotes: 0

Related Questions