objective-c - 捕获组在 NSRegularExpression 中不起作用

标签 objective-c regex ios nsregularexpression capture-group

为什么这段代码只吐出整个正则表达式匹配而不是捕获组?

输入

@"A long string containing Name:</td><td>A name here</td> amongst other things"

预期输出

A name here

实际输出

Name:</td><td>A name here</td>

代码

NSString *htmlString = @"A long string containing Name:</td><td>A name here</td> amongst other things";
NSRegularExpression *nameExpression = [NSRegularExpression regularExpressionWithPattern:@"Name:</td>.*\">(.*)</td>" options:NSRegularExpressionSearch error:nil];

NSArray *matches = [nameExpression matchesInString:htmlString
                                  options:0
                                    range:NSMakeRange(0, [htmlString length])];
for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *matchString = [htmlString substringWithRange:matchRange];
    NSLog(@"%@", matchString);
}

取自 Apple 文档的代码。 我知道还有其他库可以做到这一点,但我想坚持这项任务的内置内容。

最佳答案

您将使用以下方法访问第一个组范围:

for (NSTextCheckingResult *match in matches) {
    //NSRange matchRange = [match range];
    NSRange matchRange = [match rangeAtIndex:1];
    NSString *matchString = [htmlString substringWithRange:matchRange];
    NSLog(@"%@", matchString);
}

关于objective-c - 捕获组在 NSRegularExpression 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6822356/

相关文章:

objective-c - 将 NSTabViewItem 的副本从 NSTabView 添加到同一个 NSTabView

ios - 如何使用自动布局连续对齐 2 个按钮?

ios - 如何在 iOS map 上叠加圆圈

html - 为什么我的 XPath 与正则表达式无法匹配?

iphone - Objective-C : How to improve repetitive method implementations using method forwarding

javascript - 使用 Ajax 从 UIWebView 调用 Objective C 函数

ios - Watchkit 扩展测试类 - 访问错误问题

ios - 替代私有(private)-[UIDevice setOrientation :] for forcing camera overlay into portrait mode

Javascript 正则表达式替换不起作用

javascript - 如何替换字符串中的单词并忽略字符串中的数字