iPhone - NSScanner 无法解析

发布于 2024-11-15 05:07:06 字数 730 浏览 5 评论 0原文

我正在使用这种方法来查找第一个 <>耦合成字符串(XML 内容):

NSScanner* scanner = [NSScanner scannerWithString:contentToParse];
int startPos = 0;
int endPos = 0;

// Open search
if ([scanner scanString:@"<" intoString:nil]) {
    startPos = [scanner scanLocation]-1;
    NSLog(@"found '<' at pos %i", startPos);

    // close search
    if ([scanner scanString:@">" intoString:nil]) {
        endPos = [scanner scanLocation]-1;
        NSLog(@"found '>' at pos %i", endPos);

        NSString* tag = [contentToParse substringWithRange:NSMakeRange(startPos, endPos-startPos)];
        NSLog(@"Tag found : %@", tag);
    }
}

但仅“找到 '<' at pos 0”被记录。 我的 XML 内容包含很多很多<>项目...

为什么该方法不起作用?

I'm using this method to find the first <> couple into a string (XML content) :

NSScanner* scanner = [NSScanner scannerWithString:contentToParse];
int startPos = 0;
int endPos = 0;

// Open search
if ([scanner scanString:@"<" intoString:nil]) {
    startPos = [scanner scanLocation]-1;
    NSLog(@"found '<' at pos %i", startPos);

    // close search
    if ([scanner scanString:@">" intoString:nil]) {
        endPos = [scanner scanLocation]-1;
        NSLog(@"found '>' at pos %i", endPos);

        NSString* tag = [contentToParse substringWithRange:NSMakeRange(startPos, endPos-startPos)];
        NSLog(@"Tag found : %@", tag);
    }
}

but only "found '<' at pos 0" is logged.
My XML content contains many many <> items...

Why is that method not working ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分分钟 2024-11-22 05:07:06

scanString:intoString: 尝试扫描当前位置的字符串参数。如果当前位置不存在此类字符串,则仅返回NO

您可能需要使用 scanUpToString:intoString: (参考)相反,它会向前扫描扫描位置,直到遇到给定的字符串。

NSScanner *scanner = [NSScanner scannerWithString:contentToParse];
// open search
[scanner scanUpToString:@"<" intoString:nil];
if (![scanner isAtEnd]) {
    [scanner scanString:@"<" intoString:nil];
    // close search
    NSString *tag = nil;
    [scanner scanUpToString:@">" intoString:&tag];
    if (![scanner isAtEnd]) {
        NSLog(@"Tag found : %@", tag);
    }
}

scanString:intoString: tries to scan the string parameter at the current location. If such string is not present at the current location, it simply returns NO.

You may want use scanUpToString:intoString: (reference) instead, which scans advancing the scan location until the given string is encountered.

NSScanner *scanner = [NSScanner scannerWithString:contentToParse];
// open search
[scanner scanUpToString:@"<" intoString:nil];
if (![scanner isAtEnd]) {
    [scanner scanString:@"<" intoString:nil];
    // close search
    NSString *tag = nil;
    [scanner scanUpToString:@">" intoString:&tag];
    if (![scanner isAtEnd]) {
        NSLog(@"Tag found : %@", tag);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文