1

Objective-C: I want to remove all zeros which trail and lead with some exceptions. For example:

0.05000 -> 0.05
000.2300 -> 0.23
005.0 -> 5
500.0 -> 500
60.0000 -> 60
56.200000 -> 56.2
56.04000 -> 56.04

What I tried is something like this [.0]+$|(^0+). But it doesn't help what I'm trying to achieve. I am using NSString with RegularExpressionSearch as follows:

 NSString *cleaned = [someString stringByReplacingOccurrencesOfString:@"[.0]+$|(^0+)"
                                                                           withString:@""
                                                                              options:NSRegularExpressionSearch
                                                                                range:NSMakeRange(0, self.doseTextField.text.length)];

Any help would be appreciated.

rmaddy
  • 298,130
  • 40
  • 468
  • 517
Harsh
  • 2,702
  • 1
  • 11
  • 27

2 Answers2

2

Sometimes it is best to break tasks up, try these in order with a replacement string of @"" each time:

  1. @"^0+(?!\\.)" - an initial sequence of 0's not followed by a dot. This will trim "003.0" to "3.0" and "000.3" to "0.3".

  2. @"(?<!\\.)0+$" - a trailing sequence of zeros not preceeded by a dot. So "3.400" goes to "3.4" and "3.000" goes to "3.0"

  3. @\\.0$ - remove a trailing ".0". The first two REs may leave you with ".0" on purpose so that you can then remove the dot in this step.

This isn’t the only way to break it down but the three basic tasks are to remove leading zeros, remove trailing zeros, and cleanup. You also don't need to use REs at all, a simple finite state machine might be a good fit.

Important: The above assumes the string contains a decimal point, if it may not you need handle that as well (left as an exercise).

HTH

CRD
  • 50,500
  • 4
  • 64
  • 80
  • 1
    Good suggestion to break the problem into understandable, testable parts - six-months-from-now me greatly appreciates this sort of thing! – Kendall Lister Aug 09 '16 at 03:42
  • As this seems to be a good practice, for now am going with Wiktor's answer for a single line regex. i.e. Or try `"^(0)+(?=\\.)|^0+(?=[1-9])|\\.0+$|(\\.\\d*?)0+$"` to replace with `$1$2`. Or a grouped one: `"^(?:(0)+(?=\\.)|0+(?=[1-9]))|(?:\\.0+|(\\.\\d*?)0+)$"` – Harsh Aug 09 '16 at 17:48
-1

something like this?

let numberStrings = [
    "0.05000",
    "000.2300",
    "005.0",
    "500.0",
    "60.0000",
    "56.200000",
    "56.04000"
]

print(numberStrings.map({
    String(Double($0)!).stringByReplacingOccurrencesOfString("\\.0*$", withString: "", options: .RegularExpressionSearch, range: nil)
}))
André Slotta
  • 12,851
  • 1
  • 18
  • 30