您的位置:首页 > 移动开发 > IOS开发

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

2014-05-26 13:01 633 查看
-(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:@"<a href='user://%@'>%@</a>",str3,str3];

}
else if([str3 hasPrefix:@"http"])
{
replaceStr = [NSString stringWithFormat:@"<a href='%@'>%@</a>",str3,str3];

}
else if([str3 hasPrefix:@"#"])
{
replaceStr = [NSString stringWithFormat:@"<a href='topic://%@'>%@</a>",str3,str3];
}

if(replaceStrS!=nil)
{

test = [test stringByReplacingOccurrencesOfString:str3 withString:replaceStr];
}
NSLog(@"---->%@",test);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios