iphone - 重复应用正则表达式

标签 iphone objective-c ios regex

我有这样的文本表达式:

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'”。模式有什么问题?

最佳答案

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

关于iphone - 重复应用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7945219/

相关文章:

ios - 由于缺少入口点,场景无法访问

ios - UICollectionView - iOS 10 - 在 iPhone 6 Plus 模拟器上崩溃,但在真实设备上运行

ios - UISlider 与“设置”中的步骤类似

iphone - MonoTouch - 设置 bundle - iPhone

iphone - 如何从表格 View 中完全隐藏某个单元格?

iphone - 使用苹果的 auriotouch 示例计算频率

iphone - 如何检查电影是否正在播放? (如果可能的话)

iphone - iPhone iOS是否可以渲染弯曲的UIView?

ios - 无法从 [UIActivityViewController excludedActivityTypes] 中排除 UIActivityTypePostToFacebook

ios - 使用 Xcode 6 在 UICollectionView 中继续