objective c - Trim all zeros before and after decimal Regex -


objective-c: want remove zeros trail , lead exceptions. 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 tried [.0]+$|(^0+). doesn't i'm trying achieve. using nsstring regularexpressionsearch follows:

 nsstring *cleaned = [somestring stringbyreplacingoccurrencesofstring:@"[.0]+$|(^0+)"                                                                            withstring:@""                                                                               options:nsregularexpressionsearch                                                                                 range:nsmakerange(0, self.dosetextfield.text.length)]; 

any appreciated.

sometimes best break tasks up, try these in order replacement string of @"" each time:

  1. @"^0+(?!\\.)" - initial sequence of 0's not followed dot. trim "003.0" "3.0" , "000.3" "0.3".

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

  3. @\\.0$ - remove trailing ".0". first 2 res may leave ".0" on purpose can remove dot in step.

this isn’t way break down 3 basic tasks remove leading zeros, remove trailing zeros, , cleanup. don't need use res @ all, simple finite state machine might fit.

important: above assumes string contains decimal point, if may not need handle (left exercise).

hth


Comments