【问题标题】:Use regular expression to find and replace the string from Textfield in NSString使用正则表达式从 NSString 中的 Textfield 中查找和替换字符串
【发布时间】:2017-08-21 15:17:35
【问题描述】:

我想使用正则表达式来查找和替换字符串。在我的场景中,{3} 和 {2} 是 UITextField 标记值。根据标签值,我想替换相应的文本字段值并使用 NSExpression 计算字符串值。

示例输入字符串:

NSString *cumputedValue = @"{3}*0.42/({2}/100)^2";

注意:文本字段是根据 JSON 响应动态创建的。

【问题讨论】:

标签: ios objective-c xcode nsregularexpression


【解决方案1】:

我得到了这个问题的答案。这里 computedString 包含的值为“{3}*0.42/({2}/100)^2”。

- (NSString *)autoCalculationField: (NSString *)computedString {
    NSString *computedStringFormula = [NSString stringWithFormat:@"%@",computedString];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\d+)\\}"
                                                                           options:0
                                                                             error:nil];
    NSArray *matches = [regex matchesInString:computedStringFormula
                                      options:0
                                        range:NSMakeRange(0, computedStringFormula.length)];
    NSString *expressionStr = computedStringFormula;
    for (NSTextCheckingResult *r in matches)
    {
        NSRange numberRange = [r rangeAtIndex:1];
        NSString *newString = [NSString stringWithFormat:@"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
        expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{%@}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
    }
    NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
    return [expression expressionValueWithObject:nil context:nil];
}

- (float)getInputFieldValue: (NSString *)tagValue {
    UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
    return [tempTextFd.text floatValue];
}

【讨论】:

    【解决方案2】:

    您可以将 textField 标记与它们所代表的值一起保存在 NSDictionary 中。

    之后使用stringByReplacingOccurrencesOfString 替换您想要的值。

    类似这样的:

    for (NSString *key in dict) {
    cumputedValue = [cumputedValue stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{@%}", key] withString:[NSString stringWithFormat:@"%@", dict objectForKey:@key]];
    }
    

    这样你可以替换值

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多