views:

622

answers:

2

Hi, I am trying to build an iPhone App, where I read an RSS feed and have to parse out the id of an article from the URL. The links provided by the RSS feed are like the following: http://example.com/variable/path/components/352343/index.html

I need 352343.

So basically I need to search for at least one digit between slashes (path components could also contain digits). Regexp would be easy: "/\/(\d+)\//". But how can I do it with NSScanner?

Thanks, Ernesto

+1  A: 

You need to use it in combination with a Character set.

NSCharacterSet *charSet = [NSCharacterSet decimalDigitCharacterSet];
NSScanner *scanner = [NSScanner scannerWithString:url];
[scanner scanUpToCharactersFromSet:charSet intoString:nil];
int urlId;
[scanner scanInt:&urlId];    

Of course, this is only if you know that numbers won't appear in the URL path before the ID. If they might, you'd need to get a little more robust than this, but you could use this snippet as a starting point.

bpapa
+1  A: 

You can split your url string into parts separated by "/" and check if any part is a valid integer.

NSArray* components = [urlString componentsSeparatedByString:@"/"];
int myId;
for (NSString *comp in components){
   NSScanner *scanner = [NSScanner scannerWithString:comp];
   if ([scanner scanInt: &myId])
       return myId; 
}

or you can simply use NSString method:

int myId;
for (NSString *comp in components)
   if (myId = [comp intValue]) // intValue returns 0 if comp is not an integer
      return myId;
Vladimir
thanks very much. there is still one small gotcha: if you have a path component like '20-things' you will get 20 back. my work around: use last found integer. other possible workaround: use nsscanner (see below) to filter out digits.
ernesto che