简体   繁体   English

修剪十进制正则表达式前后的所有零

[英]Trim all zeros before and after decimal Regex

Objective-C: I want to remove all zeros which trail and lead with some exceptions. Objective-C:我想删除所有尾随和引导的零,但有一些例外。 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+) .我试过的是这样的[.0]+$|(^0+) But it doesn't help what I'm trying to achieve.但这对我想要实现的目标没有帮助。 I am using NSString with RegularExpressionSearch as follows:我将 NSString 与 RegularExpressionSearch 一起使用,如下所示:

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

Any help would be appreciated.任何帮助,将不胜感激。

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. @"^0+(?!\\\\.)" - 0 的初始序列,后面没有点。 This will trim "003.0" to "3.0" and "000.3" to "0.3".这会将“003.0”修剪为“3.0”,将“000.3”修剪为“0.3”。

  2. @"(?<!\\\\.)0+$" - a trailing sequence of zeros not preceeded by a dot. @"(?<!\\\\.)0+$" - 前面没有点的零的尾随序列。 So "3.400" goes to "3.4" and "3.000" goes to "3.0"所以“3.400”去“3.4”,“3.000”去“3.0”

  3. @\\\\.0$ - remove a trailing ".0". @\\\\.0$ - 删除尾随的“.0”。 The first two REs may leave you with ".0" on purpose so that you can then remove the dot in this step.前两个 RE 可能会故意留下“.0” 以便您可以在此步骤中删除点。

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.您也根本不需要使用 RE,一个简单的有限状态机可能很合适。

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 HTH

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)
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM