IOS--正则表达式的使用(字符串的查找和替换)

-(void)parseLink
{
    NSError* error = NULL;
    //(encoding=\")[^\"]+(\")
    //分成三段来理解
    /*
     第一段:以某段字符做为起始 (encoding=\") 括号内为实际内容
     第二段:对于包含中的定义,参见正则.
     第三段:再以某段字符做为收尾 (\")
     */
    
    NSString *test = @"#dsadsadas# http://www.badidu.com 我的";
    
    NSString *regexStr = @"(@\\w+)|(#\\w+#)|(http(s)?://([A-Za-z0-9._-]+(/)?)*)";
    
    
    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexStr
                                                                           options:0
                                                                             error:&error];
    
    NSArray *array = [regex matchesInString:test options:0 range:NSMakeRange(0, test.length)];
    
    
    NSMutableArray *replaceStrS = [[NSMutableArray alloc]initWithCapacity:array.count];
    
    
    for(NSTextCheckingResult  *str2 in array)
    {
    
        NSString *str = [test substringWithRange:str2.range];
        
        [replaceStrS addObject:str];
    }
    
    for(NSString *str3 in replaceStrS)
    {
      
        NSString *replaceStr = nil;
        
        if([str3 hasPrefix:@"@"])
        {
            
            replaceStr = [NSString stringWithFormat:@"%@",str3,str3];
        
        }
        else if([str3 hasPrefix:@"http"])
        {
            replaceStr = [NSString stringWithFormat:@"%@",str3,str3];
        
        }
        else if([str3 hasPrefix:@"#"])
        {
            replaceStr = [NSString stringWithFormat:@"%@",str3,str3];
        }
        
        if(replaceStrS!=nil)
        {
        
            test = [test stringByReplacingOccurrencesOfString:str3 withString:replaceStr];
        }
        NSLog(@"---->%@",test);
    }
}


你可能感兴趣的:(IOS_IKeD)