Using NSRegularExpression to extract URLs on the iPhone

The method matchesInString:options:range: returns an array of NSTextCheckingResult objects. You can use fast enumeration to iterate through the array, pull out the substring of each match from your original string, and add the substring to a new array. NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@”http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?” options:NSRegularExpressionCaseInsensitive error:&error]; NSArray *arrayOfAllMatches = [regex matchesInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])]; NSMutableArray … Read more

How to write regular expressions in Objective C (NSRegularExpression)?

A NSTextCheckingResult has multiple items obtained by indexing into it. [match rangeAtIndex:0]; is the full match. [match rangeAtIndex:1]; (if it exists) is the first capture group match. etc. You can use something like this: NSString *searchedString = @”domain-name.tld.tld2″; NSRange searchedRange = NSMakeRange(0, [searchedString length]); NSString *pattern = @”(?:www\\.)?((?!-)[a-zA-Z0-9-]{2,63}(?<!-))\\.?((?:[a-zA-Z0-9]{2,})?(?:\\.[a-zA-Z0-9]{2,})?)”; NSError *error = nil; NSRegularExpression* regex = … Read more

How to validate an e-mail address in swift?

I would use NSPredicate: func isValidEmail(_ email: String) -> Bool { let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}” let emailPred = NSPredicate(format:”SELF MATCHES %@”, emailRegEx) return emailPred.evaluate(with: email) } for versions of Swift earlier than 3.0: func isValidEmail(email: String) -> Bool { let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}” let emailPred = NSPredicate(format:”SELF MATCHES %@”, emailRegEx) return emailPred.evaluate(with: email) } for … Read more