用 NSArray 中的对象替换 NSString 中的数字

发布于 2024-11-18 23:30:31 字数 445 浏览 3 评论 0原文

在 UITextView 中,用户可以输入 {{1}}{{177}} 格式的数字。在预览字段中,就像这里一样,我想用 NSArray 中的值替换该模式,其中数字对应于数组中的行。

我有两个想法来解决这个问题:

  1. 用 NSRegularExpression 计算所有出现的次数,循环遍历它们并替换它们。
  2. 从 NSString 创建一个单词数组并循环遍历该数组,替换出现的位置并将 NSString 重新组合在一起。

这两个选项中哪一个性能更高、更可靠?还有别的办法吗?

--更新-- 这是查找模式的正则表达式:@"\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][ 0-9])\\}\\}"。如何在带有整数的循环中使用它来替换模式?

In a UITextView users can enter numbers formatted like {{1}} or {{177}}. In a preview field, much like here on SO I'd like to replace that pattern with a value from an NSArray, where the number corresponds to the row in the array.

I have two ideas to solve this:

  1. Count all occurrences with an NSRegularExpression, loop through them and replace them.
  2. Create a word-array out of the NSString and loop through the array, replacing occurrences and put the NSString back together.

Which of those two options is more performant and reliable? Is there another way?

-- update --
This is the regular expression to find the pattern: @"\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}". How can I use this in a loop with an integer to replace the pattern?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

荒人说梦 2024-11-25 23:30:32

我会使用第二种方法,因为它似乎比使用正则表达式更方便(尽管我承认对它们不是很有经验)。

给定一个输入字符串 NSString* input 我将过滤掉非数字字符,如下所示:

NSCharacterSet* notNumbersSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSArray * wholeNumbers = [input componentsSeparatedByCharactersInSet:notNumbersSet];

现在循环遍历整数数组:

for( NSString* numString in wholeNumbers ) {
    NSInteger num = [numString intValue];
    // ...
}

I would use the second approach since it seems more convenient than using regular expressions (although I'm admittedly not very experienced with them).

Given an input string NSString* input I would filter out not numeric characters as follows:

NSCharacterSet* notNumbersSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSArray * wholeNumbers = [input componentsSeparatedByCharactersInSet:notNumbersSet];

Now loop through the array of whole numbers:

for( NSString* numString in wholeNumbers ) {
    NSInteger num = [numString intValue];
    // ...
}
灼疼热情 2024-11-25 23:30:32

NSRegularExpression 方法是这样的——

NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{(\\d+?)\\}\\}"
                                                                             options:0
                                                                               error:nil];
NSMutableString * resultString = [aString mutableCopy];
NSTextCheckingResult * result;
NSUInteger location = 0;

/* Get the first match in the remaining string to search */
while ((result = [expression firstMatchInString:resultString options:0 range:NSMakeRange(location, [resultString length] - location)])) {

    /* Get the index of the array using the capture group 1 i.e. (\\d+?) */
    NSUInteger index = [[resultString substringWithRange:[result rangeAtIndex:1]] integerValue];

    /* Get the string that will replace the match */
    NSString * replacementString = [replacementStrings objectAtIndex:index];

    /* Replace the string */
    [resultString replaceCharactersInRange:result.range withString:replacementString];

    /* Skip to the end of the replaced string */
    location = result.range.location + [replacementString length];
}

由于我们的替换字符串来自数组,我怀疑我们是否有一个单一语句的解决方案。在这里,我们找到一个匹配项,适当地替换它,然后在字符串的其余部分中搜索匹配项。我们重复这一点,没有更多结果。

A NSRegularExpression approach would be something like this –

NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{(\\d+?)\\}\\}"
                                                                             options:0
                                                                               error:nil];
NSMutableString * resultString = [aString mutableCopy];
NSTextCheckingResult * result;
NSUInteger location = 0;

/* Get the first match in the remaining string to search */
while ((result = [expression firstMatchInString:resultString options:0 range:NSMakeRange(location, [resultString length] - location)])) {

    /* Get the index of the array using the capture group 1 i.e. (\\d+?) */
    NSUInteger index = [[resultString substringWithRange:[result rangeAtIndex:1]] integerValue];

    /* Get the string that will replace the match */
    NSString * replacementString = [replacementStrings objectAtIndex:index];

    /* Replace the string */
    [resultString replaceCharactersInRange:result.range withString:replacementString];

    /* Skip to the end of the replaced string */
    location = result.range.location + [replacementString length];
}

Since our replacement strings come from an array I doubt we have a single statement solution to this. Here we find a match, replace it appropriately and then search the rest of the string for a match. We repeat this there are no more results.

笑脸一如从前 2024-11-25 23:30:31

这是使用 NSRegularExpression 的答案:

NSString * input = @"{{83}} fjsdkfjds {{122}}";

NSMutableString * strToMakeReplacements = [[NSMutableString alloc] initWithString:input];

NSError * error = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}" options:NSRegularExpressionCaseInsensitive    error:&error];

NSArray * matches = [regex matchesInString:input options:NSMatchingReportProgress range:NSMakeRange(0, [input length])];

for (int i = [matches count]-1; i>=0 ; i--) {
    NSTextCheckingResult * match = [matches objectAtIndex:i];

    NSRange matchRange = match.range;
    NSString * numString = [input substringWithRange:NSMakeRange(matchRange.location+2, matchRange.length-4)];
    NSInteger num = [numString intValue];

    NSString * replacementValue = [self replacementValueForNum:num]; // write this function yourself

    [strToMakeReplacements replaceCharactersInRange:match.range withString:replacementValue];
}

请注意,您需要转义正则表达式中的斜杠,以便它变为 \\{\\{([1-9]|[1-9] [0-9]|[1-9][0-9][0-9])\\}\\}

Here's an answers using NSRegularExpression:

NSString * input = @"{{83}} fjsdkfjds {{122}}";

NSMutableString * strToMakeReplacements = [[NSMutableString alloc] initWithString:input];

NSError * error = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}" options:NSRegularExpressionCaseInsensitive    error:&error];

NSArray * matches = [regex matchesInString:input options:NSMatchingReportProgress range:NSMakeRange(0, [input length])];

for (int i = [matches count]-1; i>=0 ; i--) {
    NSTextCheckingResult * match = [matches objectAtIndex:i];

    NSRange matchRange = match.range;
    NSString * numString = [input substringWithRange:NSMakeRange(matchRange.location+2, matchRange.length-4)];
    NSInteger num = [numString intValue];

    NSString * replacementValue = [self replacementValueForNum:num]; // write this function yourself

    [strToMakeReplacements replaceCharactersInRange:match.range withString:replacementValue];
}

Note that you need to escape the slashes in your regex, so that it becomes \\{\\{([1-9]|[1-9][0-9]|[1-9][0-9][0-9])\\}\\}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文