0

我试着评价这句话:

<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);

我测试了几个正则表达式,但我没有成功,有人可以帮助我吗?

4

3 回答 3

0
testArray = [[NSArray alloc] init];
NSString *testString = [[NSString alloc] initWithFormat:@"0.309804,0.784314,0.992157"];
testArray = [testString componentsSeparatedByString:@","];

现在你可以使用 testArray 中的值了。您也可以将其转换为 int 或 float

于 2013-05-14T09:39:07.187 回答
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

于 2013-05-14T09:49:32.933 回答
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);
于 2013-05-14T09:51:38.467 回答