使用正则表达式查找和替换 NSString 中 Textfield 中的字符串

Use regular expression to find and replace the string from Textfield in NSString

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

示例输入字符串:

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

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

您可以将 textField 标签保存在 NSDictionary 中,其中包含它们所代表的值。

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

像这样:

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

这样你就可以替换值

我得到了这个问题的答案。这里的 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];
}