0

I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.

Sample Input String :

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

Note: The textFields are created dynamically based on JSON response.

Muthu Sabarinathan
  • 1,198
  • 2
  • 21
  • 49

2 Answers2

1

I got the answer for this question. Here the computedString contains the value as "{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];
}
Muthu Sabarinathan
  • 1,198
  • 2
  • 21
  • 49
0

You could save the textField tags in a NSDictionary with the value that they represent.

After that use stringByReplacingOccurrencesOfString to replace the values that you wish to.

Something like this:

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

This way you can have the values replaced

Ricardo Alves
  • 642
  • 2
  • 13
  • 34