Re: NSScanner baffling behaviour (scanString:intoString: doesn't work!)
Re: NSScanner baffling behaviour (scanString:intoString: doesn't work!)
- Subject: Re: NSScanner baffling behaviour (scanString:intoString: doesn't work!)
- From: Greg Titus <email@hidden>
- Date: Tue, 8 Apr 2003 08:30:01 -0700
On Tuesday, April 8, 2003, at 02:51 AM, Greg Hurrell wrote:
Can anyone tell me why the following method isn't working?
[...]
What actually happens when I run this code? It returns nil because
startTag is never found.
Apple's NSScanner docs say (of scanString:intoString:), "Invoke this
method with nil as stringValue to simply scan past a given string."
Sounds simple, but it doesn't work. It appears to never find the
startTag, even when I know it's in there. After the first attempt at
scanning for the startTag the scanLocation is still at 0.
You are misunderstanding the docs. The -scanString:intoString: method
is for scanning past a given string that is already at the scan
location. It doesn't search for the string, it simply reads it if it is
already at that position.
You need to scanUpTo your start tag, then scan the start tag itself,
then scanUpTo your end tag. Like so:
// scan a string (source) for material between startTag and endTag
+ (NSString *)_scanString:(NSString *)source
startTag:(NSString *)startTag
endTag:(NSString *)endTag
{
NSScanner *scanner = [NSScanner scannerWithString:source];
NSString *result = nil;
// find start tag
if (![scanner scanUpToString:startTag intoString:nil])
// startTag not found!
return nil;
// skip over the start tag we found
[scanner scanString:startTag intoString:nil];
// then scan up to the end tag in the result
[scanner scanUpToString:endTag intoString:&result];
// see if the end tag actually exists, if so return the result, if
not return nil
if ([scanner scanString:endTag intoString:nil])
return result;
else
return nil;
}
Hope this helps,
- Greg
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.