2011-10-30 24 views
0

我有文字表述是这样的:应用正则表达式多次

HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4' 

我要提取下面的文本块:

HIUPD:bla2bla2' 

而且

HIUPD:bla3bla3' 

我Objective- C代码如下所示:

-(void) ermittleKonten:(NSString*) bankNachricht 
{ 
    NSRegularExpression* regexp; 
    NSTextCheckingResult* tcr; 
    regexp = [NSRegularExpression regularExpressionWithPattern:@"HIUPD.*'" options:0 error:nil]; 

    int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])]; 
    for(int i = 0; i < numAccounts; ++i) { 
     tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])]; 
     NSString* HIUPD = [bankNachricht substringWithRange:tcr.range]; 
     NSLog(@"Found text is:\n%@", HIUPD); 
    } 
} 

在Objective-C代码NUMACCOUNTS个是1,但应该是2,这是找到该字符串是“HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4' ”

我测试的正则表达式模式与在线工具(http://www.regexplanet.com/simple/index.html)。在在线工具中,它工作正常,并提供2个结果,因为我希望它是。

但我希望在ios代码中有相同的结果,即“HIUPD:bla2bla2”和“HIUPD:bla3bla3”。模式有什么问题?

回答

2

您正在执行与.*的贪婪匹配,因此正则表达式在.*中捕获的次数尽可能多。您应该做.*?[^']*,以便*不能匹配'