2012-09-18 52 views

回答

1

有沒有在預期的效果有些含糊不清。例如,如果結果是「ABC( 202 * 10)「或」ABC(2020)「?我要去assu我後者。由於正則表達式是相當通用的,下面是一個Perl片段,它完成了我認爲你想要的東西,然後將它翻譯成Cocoa。我已經給出了兩個,因爲在移動到NSRegularExpression之前,更容易看到發生了什麼,因爲後者在模式中有更多的轉義。

Perl版本:

#!/usr/bin/perl -w 
use strict; 


my $search_text = "((Col(202)/Col(201)-1)*100"; 

$search_text =~ s|Col\((?P<num>\d+)\)|ABC($+{num}0)|g; 
print $search_text; 

打印:((ABC(2020)/ABC(2010)-1)*100

所以,匹配模式是Col\((?P<num>\d+)\)且取代類型ABC($+{num}0

可可版本:

#import <Foundation/Foundation.h> 

int main(int argc, char *argv[]) { 
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init]; 

    NSRegularExpression *regex = nil; 
    regex = [NSRegularExpression regularExpressionWithPattern:@"Col\\((\\d+)\\)" options:NSRegularExpressionCaseInsensitive error:nil]; 
    NSString *searchText = @"((Col(202)/Col(201)-1)*100"; 
    NSString *newText = [regex stringByReplacingMatchesInString:searchText options:0 range:NSMakeRange(0,[searchText length]) withTemplate:@"ABC($10)"]; 
    NSLog(@"new = %@",newText); 
    [p release]; 
} 

日誌:

2012-09-18 12:30:26.880 Untitled[22405:707] new = ((ABC(2020)/ABC(2010)-1)*100 

現在,如果我原來的設想是錯誤的,你從字面上想要的「民* 10」的結果,那麼替代模式是:

@"ABC($1 * 10)" 
+0

非常感謝艾倫... – Ben861305