objective-cregexnsregularexpressionnsstringencoding

Finding substring of NSString with RegularExpressions


I'm trying to get the substring from a NSString by using NSRegularExpression. I don't want the number of matches or to replace the string, I want the string that matches the Regular Expression

NSString *string = <a>www.apple.com</a>
NSError *error;
[NSRegularExpression regularExpressionWithPattern:@"(\b(https?|ftp|file)://)?[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *substring;

What I'm looking for is:

substring = www.apple.com;

I'm trying to use as little NSRange/NSMakeRange as possible. Can anyone help me, please?


Solution

  • NSRange *range = [string rangeOfString:@"(\b(https?|ftp|file)://)?[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]" options:NSRegularExpressionSearch];
    if(range.location!=NSNotFound) {
    NSString *neededSubString = [String SubStringWithRange:range];
    }
    

    in this code we first get the range of the string that matches the regular expression. then we are getting the substring from that range