【问题标题】:ios how to replace comma with dot in a NSString, but only for numbers?ios如何在NSString中用点替换逗号,但仅适用于数字?
【发布时间】:2012-04-03 23:22:05
【问题描述】:

假设我有一个这种格式的字符串:

“1,3 升水,2,5 磅的东西,1,4 磅的东西”

我想从字符串中获取一个包含元素的数组,元素用“,”分隔。

如何将“,”替换为“。”,但只有在 2 位数字之间?

所以初始数组看起来像: “1.3 升水,2.5 磅的东西,1.4 磅的东西”

谢谢

【问题讨论】:

    标签: objective-c ios regex replace nsregularexpression


    【解决方案1】:

    一般来说,创建一个执行以下操作的正则表达式: 将(\d+),(\d+) 替换为$1\.$2

    http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

    【讨论】:

      【解决方案2】:

      您可以使用正则表达式来完成:

      NSString *string = @"1,3 litres of water, 2,5 pounds of something ,1,4 pounds of something else";
      NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([0-9]+),([0-9]+)" options:0 error:nil];
      NSString * newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, string.length) withTemplate:@"$1.$2"];
      NSLog(@"%@", newString); // 1.3 litres of water, 2.5 pounds of something ,1.4 pounds of something else
      

      现在如果你想把它分成一个数组,你可以这样做:

      NSArray *array = [newString componentsSeparatedByString:@","];
      

      【讨论】:

        猜你喜欢
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 2016-09-05
        • 2018-07-06
        • 2013-06-23
        • 2022-11-19
        • 1970-01-01
        相关资源
        最近更新 更多