簡體   English   中英

使用正則表達式查找並替換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";

注意:textFields是基於JSON響應動態創建的。

我得到了這個問題的答案。 此處,calculatedString包含值為“ {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];
}

您可以將textField標記及其表示的值保存在NSDictionary中。

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

像這樣:

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

這樣您可以替換值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM