NSRegularExpression 用于提取两个 XML 标签之间的文本
如何使用 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。
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>
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.
NOTE: I don't want to use NSXMLParser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例:
NSLog 输出:
Example:
NSLog output:
在 swift 3.0 中执行此操作
P.S:这是 @zaph 在 obj-c 中的解决方案的相应快速解决方案
To do it in swift 3.0
P.S : This is corresponding swift solution of @zaph's solution in obj-c