本文介绍了NSRegularExpression提取两个XML标签之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用NSRegularExpression在"badgeCount"标签之间提取值"6".以下是服务器的响应:
How to extract the value "6" between the "badgeCount" tags using NSRegularExpression. Following is the response from the server:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><badgeCount>6</badgeCount><rank>2</rank><screenName>myName</screenName>
以下是我尝试但未成功的代码.实际上,它进入了其他部分并显示正则表达式的值为nil":
Following is the code I tried but not getting success. Actually it goes in else part and prints "Value of regex is nil":
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");
如果您可以提供示例代码,将不胜感激.
If you could provide sample code that would be much appreciated.
注意:我不想使用NSXMLParser.
NOTE: I don't want to use NSXMLParser.
推荐答案
示例:
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'
这篇关于NSRegularExpression提取两个XML标签之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!