繁体   English   中英

iOS:在目标C中提取NSString的子字符串

[英]iOS: extract substring of NSString in objective C

我有一个NSString作为:

"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321<\/a>"

我需要从其中提取NSString末尾附近的12321并存储。 首先我尝试

        NSString *shipNumHtml=[mValues objectAtIndex:1];
        NSInteger htmlLen=[shipNumHtml length];

        NSString *shipNum=[[shipNumHtml substringFromIndex:htmlLen-12]substringToIndex:8];

但是后来我发现数字12321可以是可变长度的。

我找不到像java的indexOf()这样的方法来找到'>''<' ,然后找到具有这些索引的子字符串。 我在SO上找到的所有答案要么知道要搜索的子字符串,要么知道子字符串的位置。 有什么帮助吗?

我通常不提倡使用正则表达式来解析HTML内容,但是看起来正则表达式匹配>(\\d+)<可以在此简单字符串中完成工作。

这是一个简单的示例:

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@">(\\d+)<"
                                                                       options:0
                                                                         error:&error];
// Handle error != nil

NSTextCheckingResult *match = [regex firstMatchInString:string
                                                options:0
                                                  range:NSMakeRange(0, [string length])];
if (match) {
    NSRange matchRange = [match rangeAtIndex:1];
    NSString *number = [string substringWithRange:matchRange]
    NSLog(@"Number: %@", number);
}

就像@HaneTV所说的那样,您可以使用NSString方法rangeOfString搜索子字符串。 由于字符“>”和“ <”出现在字符串中的多个位置,因此您可能需要查看NSRegularExpression和/或NSScanner。

这可能对您有所帮助,我刚刚进行了测试:

NSString *_string = @"<a href='javascript:void(null)' onclick='handleCommandForAnchor(this, 10);return false;'>12321</a>";
NSError *_error;
NSRegularExpression *_regExp = [NSRegularExpression regularExpressionWithPattern:@">(.*)<" options:NSRegularExpressionCaseInsensitive error:&_error];
NSArray *_matchesInString = [_regExp matchesInString:_string options:NSMatchingReportCompletion range:NSMakeRange(0, _string.length)];
[_matchesInString enumerateObjectsUsingBlock:^(NSTextCheckingResult * result, NSUInteger idx, BOOL *stop) {
    for (int i = 0; i < result.numberOfRanges; i++) {
        NSString *_match = [_string substringWithRange:[result rangeAtIndex:i]];
        NSLog(@"%@", _match);
    }
}];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM