什么是最好的解决方案?扫描

时间:2014-03-09 12:46:57

标签: ios objective-c nsstring

我有一个字符串:@" ololo width: 350px jijiji width:440px ... text=12... " 我想将@“width:”之后的所有数字替换为280.所以在扫描之后,它应该是:

@" ololo width: 280px jijiji width: 280px ... text=12... "

什么是最佳解决方案?

1 个答案:

答案 0 :(得分:3)

您可以使用正则表达式:

NSString *string = @" ololo width: 350px jijiji width:440px ... text=12... ";
NSMutableString *replaced = [string mutableCopy];

NSString *pattern = @"(width:\\s*)(\\d+)(px)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:0
                                                                         error:NULL];
[regex replaceMatchesInString:replaced options:0 range:NSMakeRange(0, replaced.length)
                 withTemplate:@"$1280$3"];

该模式有三个“捕获组”:

  • 第一个匹配字符串“width:”,可选地后跟一些空格
  • 第二个匹配一个或多个数字,
  • 第三个匹配字符串“px”。

保留第一个和第三个捕获组($1$3 在替换模板中),第二个替换为280。


(根据您的评论更新:)如果您需要匹配的字符串 (“350”,“440”) 然后它稍微复杂一些。而不是replaceMatchesInString: 你可以使用enumerateMatchesInString:

[regex enumerateMatchesInString:replaced
                        options:0
                          range:NSMakeRange(0, [replaced length])
                     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
             // range = location of the regex capture group "(\\d+)":
             NSRange range = [result rangeAtIndex:2];
             // Get old width:
             NSString *oldWidth = [replaced substringWithRange:range];
             NSLog(@"old width=%@", oldWidth);
             // Replace with new width :
             NSString *newWidth = @"280";
             [replaced replaceCharactersInRange:range withString:newWidth];
         }
 ];