我试着评估这句话:
<font color="0.839216,0.839216,0.839216" strokeColor="none" size="35" face="Avenir-Book">
我需要提取颜色属性的3个浮点值
使用此代码:
NSRegularExpression* colorRegex = [[[NSRegularExpression alloc] initWithPattern:@"color=([0-9]+),([0-9]+),([0-9]+)" options:0 error:NULL] autorelease];
[colorRegex enumerateMatchesInString:tag options:0 range:NSMakeRange(0, [tag length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSNumber *redComponent=[NSNumber numberWithFloat: [[tag substringWithRange: match.range] floatValue] ];
NSNumber *greenComponent=[NSNumber numberWithFloat: [[tag substringWithRange: match.range ] floatValue] ];
NSNumber *blueComponent=[NSNumber numberWithFloat: [[tag substringWithRange: match.range] floatValue] ];
self.color=[[UIColor alloc] initWithRed:redComponent.floatValue green:greenComponent.floatValue blue:blueComponent.floatValue alpha:1];
NSLog(@"color %@,%@,%@",redComponent,greenComponent,blueComponent);
我测试了几个正则表达式,但我没有成功,有人可以帮助我吗?
答案 0 :(得分:0)
testArray = [[NSArray alloc] init];
NSString *testString = [[NSString alloc] initWithFormat:@"0.309804,0.784314,0.992157"];
testArray = [testString componentsSeparatedByString:@","];
现在你可以使用testArray中的值。您也可以将其转换为int或float
答案 1 :(得分:0)
试试这个:
NSString *color = @"color=0.309804,0.784314,0.992157";
color = [color stringByReplacingOccurrencesOfString:@"color=" withString:@""];
NSArray *arrColor = [color componentsSeparatedByString:@","];
NSNumber *redComponent;
NSNumber *greenComponent;
NSNumber *blueComponent;
for (int i = 0; i < [arrColor count]; i++) {
if (i == 0) redComponent=[NSNumber numberWithFloat:[[arrColor objectAtIndex:i] floatValue]];
if (i == 1) greenComponent=[NSNumber numberWithFloat:[[arrColor objectAtIndex:i] floatValue]];
if (i == 2) blueComponent=[NSNumber numberWithFloat:[[arrColor objectAtIndex:i] floatValue]];
}
NSLog(@"color %@,%@,%@",redComponent,greenComponent,blueComponent);
<强>输出:强>
颜色0.309804,0.784314,0.992157
答案 2 :(得分:0)
您的模式与引号"
和点.
不匹配,因此它应如下所示:
initWithPattern:@"color=\"([0-9.]+),([0-9.]+),([0-9.]+)\""
在块中,你必须使用rangeAtIndex:
来获取捕获组的值,所以这看起来像(简化你的代码):
float redComponent = [[tag substringWithRange: [match rangeAtIndex:1]] floatValue];
float greenComponent = [[tag substringWithRange: [match rangeAtIndex:2]] floatValue];
float blueComponent = [[tag substringWithRange: [match rangeAtIndex:3]] floatValue];
self.color = [[UIColor alloc] initWithRed:redComponent green:greenComponent blue:blueComponent alpha:1];
NSLog(@"color %f,%f,%f", redComponent, greenComponent, blueComponent);