【问题标题】:Issue with Xml parsing Using Regex使用正则表达式解析 Xml 的问题
【发布时间】:2013-05-06 06:59:08
【问题描述】:

这是我通过 web 服务收到的 xml..

<?xml version="1.0" encoding="utf-8"?>
<Quotes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://swanandmokashi.com">
  <QuoteOfTheDay>Hit any user to continue.</QuoteOfTheDay>
  <Author>Fuzzel Fish Administration Page</Author>
</Quotes>

我试图在我的 connectionDidFinishLoading 中通过这个来解析它:...

{            
 webData_str=[[NSString alloc]initWithData:webData encoding:NSUTF8StringEncoding];
 NSString *pattern = @"<QuoteOfTheDay>(.*)</QuoteOfTheDay><Author>(.*)</Author>";
 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                        options:NSRegularExpressionCaseInsensitive                                                                            error:nil];

__block NSString *QuoteString,*author= nil;

[regex enumerateMatchesInString:webData_str options:0 range:NSMakeRange(0, [webData_str length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {

   // not executing...

    if (0 < [match numberOfRanges]) {
        NSRange range = [match rangeAtIndex:1];
        QuoteString = [webData_str substringWithRange:range];


        NSRange range1 = [match rangeAtIndex:2];
        author = [webData_str substringWithRange:range1];        

    }
}];        

final=[NSString stringWithFormat:@"\n%@\n%@",QuoteString,author];
NSLog(@"Final--- %@",final);
}

这有什么问题? , 执行流程不在块内..

【问题讨论】:

    标签: iphone objective-c regex xml-parsing


    【解决方案1】:

    更好的解决方案是使用 XML 解析器(例如 NSXMLParser)而不是常规 表达式。

    但是要回答您的具体问题:您的正则表达式与&lt;/QuoteOfTheDay&gt;&lt;Author&gt; 之间的空格(换行符和空格)不匹配。如果您将模式更改为

    NSString *pattern = @"<QuoteOfTheDay>(.*)</QuoteOfTheDay>\\s*<Author>(.*)</Author>";
    

    你会得到预期的输出。

    【讨论】:

    • 完美..谢谢.. 是的 NSXMlParser 会是更好的选择,但由于标签数量只有两个,我会选择正则表达式..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2016-01-06
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多