捕获组无法在NSRegularExpression中工作 [英] Capture groups not working in NSRegularExpression
本文介绍了捕获组无法在NSRegularExpression中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么此代码只吐出整个正则表达式匹配而不是捕获组?
Why is this code only spitting out the entire regex match instead of the 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文档获取的代码. 我知道还有其他库可以执行此操作,但是我想坚持执行此任务的内置功能.</em>
Code taken from Apple docs. I know there are other libraries to do this but i want to stick with what's built in for this task.
推荐答案
您将使用:
for (NSTextCheckingResult *match in matches) {
//NSRange matchRange = [match range];
NSRange matchRange = [match rangeAtIndex:1];
NSString *matchString = [htmlString substringWithRange:matchRange];
NSLog(@"%@", matchString);
}
这篇关于捕获组无法在NSRegularExpression中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文