views:

184

answers:

1

Hello, I have the following code:

NSString *text = @"http://bit.ly/111 http://bit.ly/222 http://www.www.www";
NSRegularExpression *aLinkRegex = [NSRegularExpression regularExpressionWithPattern:@".*http://.*" options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger numberOfMatches = [aLinkRegex numberOfMatchesInString:text options:0 range:NSMakeRange(0, [text length])];

I want to find the number of http's in the text (I know this isn't a good regex), but numberOfMatchesInString always returns 1, while it should return 3 in the above code.

Could someone please tell me what's wrong with the above code?

Cheers,

+1  A: 

There is only one match, because your regular expression matches the first http:// and the .* "eats" the rest of the string.

Why not search for something more like:

http://

or if you are trying to capture each URL in full, something like:

http://[^ ]*

Which means search for anything after http:// that is not a space.

You should really look into reading through some kind of regular expression guide.

Kendall Helmstetter Gelner
This explains a lot. I really need to read more about regular expressions. Thank you Kendall, you're the best.
Mota
Mota: Even better would be to use John Gruber's URL-matching regex (assuming it works with NSRegularExpression) http://daringfireball.net/2010/07/improved_regex_for_matching_urls or Stephen Holt's AutoHyperlinks framework: https://bitbucket.org/sholt/autohyperlinks2/wiki/Home
Peter Hosey
I was going to mention that, although if he just has a series of space separated URL's a simpler approach would be a lot cheaper to parse.Come to think of it, if that's the case he really should just use componentsSeperatedByString
Kendall Helmstetter Gelner