8

如何使用 NSRegularExpression 提取“badgeCount”标签之间的值“6”。以下是来自服务器的响应:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><badgeCount>6</badgeCount><rank>2</rank><screenName>myName</screenName>

以下是我尝试但没有成功的代码。实际上它进入其他部分并打印“正则表达式的值为零”:

NSString *responseString =   [[NSString alloc] initWithBytes:[responseDataForCrntUser bytes] length:responseDataForCrntUser.length encoding:NSUTF8StringEncoding];

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=badgeCount>)(?:[^])*?(?=</badgeCount)" options:0 error:&error];
if (regex != nil) {
    NSTextCheckingResult *firstMatch = [regex firstMatchInString:responseString options:0 range:NSMakeRange(0, [responseString length])];
    NSLog(@"NOT NIL");
    if (firstMatch) {
        NSRange accessTokenRange = [firstMatch rangeAtIndex:1];
        NSString *value = [urlString substringWithRange:accessTokenRange];
        NSLog(@"Value: %@", value);
    }
}
else
    NSLog(@"Value of regex is nil");

如果您能提供示例代码,将不胜感激。

注意:我不想使用 NSXMLParser。

4

2 回答 2

18

例子:

NSString *xml = @"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><badgeCount>6</badgeCount><rank>2</rank><screenName>myName</screenName>";
NSString *pattern = @"<badgeCount>(\\d+)</badgeCount>";

NSRegularExpression *regex = [NSRegularExpression
                                      regularExpressionWithPattern:pattern
                                      options:NSRegularExpressionCaseInsensitive
                                      error:nil];
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:xml options:0 range:NSMakeRange(0, xml.length)];

NSRange matchRange = [textCheckingResult rangeAtIndex:1];
NSString *match = [xml substringWithRange:matchRange];
NSLog(@"Found string '%@'", match);

NSLog 输出:

Found string '6'
于 2011-10-05T12:49:31.403 回答
4

在 swift 3.0 中完成

func getMatchingValueFrom(strXML:String, tag:String) -> String {
    let pattern : String = "<"+tag+">(.*?)</"+tag+">" // original didn't work: "<"+tag+">(\\d+)</"+tag+">"
    let regexOptions = NSRegularExpression.Options.caseInsensitive
    
    do {
        let regex = try NSRegularExpression(pattern: pattern, options: regexOptions)
        let textCheckingResult : NSTextCheckingResult = regex.firstMatch(in: strXML, options: NSRegularExpression.MatchingOptions(rawValue: UInt(0)), range: NSMakeRange(0, strXML.count))!
        let matchRange : NSRange = textCheckingResult.range(at: 1)
        let match : String = (strXML as NSString).substring(with: matchRange)
        return match
    } catch {
        print(pattern + "<-- not found in string -->" + strXML )
        return ""
    }
}

PS:这是@zaph在obj-c中的解决方案对应的快速解决方案

于 2016-09-20T05:49:21.960 回答