0

我有

NSString *str =  @"<0x112233><0x112233><0x112233>0a";

我希望将这些数据保存在 nsarray

nsarray  : { 0x112233 0x112233 0x112233 }

只保存包含在“<>”中的数据并忽略所有其他数据。

我试过这样的正则表达式

NSString *str =  @"<0x112233><0x112233><0x112233>0a";

NSError *error2;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(.*)>"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error2];
if (error2)
{
    NSLog(@"Error %@", [error2 description]);
}

NSArray *payloadRanges=[regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];


NSLog(@"data %@",payloadRanges);

但我给了我这个输出:

data (
    "<NSSimpleRegularExpressionCheckingResult: 0x1ddc5e30>{0, 30}{<NSRegularExpression: 0x1f078710> <(.*)> 0x1}"
)
4

4 回答 4

5

(正如 Pat Teen 在评论中所说),您的模式是greedy,这意味着第一个匹配项尽可能多地获得,即整个字符串。

您可以通过将模式更改@"<(.*)>"@"<(.*?)>".

然后payloadRanges是三个NSTextCheckingResult对象的数组:

(
    "<NSSimpleRegularExpressionCheckingResult: 0x10010af40>{0, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}",
    "<NSSimpleRegularExpressionCheckingResult: 0x10010c210>{10, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}",
    "<NSSimpleRegularExpressionCheckingResult: 0x10010c250>{20, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}"
)

现在您必须(...)从每个结果中提取与组匹配的子字符串:

NSMutableArray *data = [NSMutableArray array];
for (NSTextCheckingResult *result in payloadRanges) {
    [data addObject:[str substringWithRange:[result rangeAtIndex:1]]];
}
NSLog(@"data %@",data);

输出:

data (
    0x112233,
    0x112233,
    0x112233
)
于 2013-10-26T11:39:11.000 回答
1

酷,试试这个简单的手动硬编码行,而不使用任何注册专家:

NSString *convert =[str stringByReplacingOccurrencesOfString:@"<" withString:@""];

    convert= [convert stringByReplacingOccurrencesOfString:@">" withString:@" "];
    NSLog(@"con %@",convert);
    NSMutableArray *array = (NSMutableArray *)[convert componentsSeparatedByString:@" "];
    NSLog(@"%@" ,array);

    for(NSString *str in array){
        if([str length]<4){
            [array removeObject:str];
        }

    }
    NSLog(@"%@",array);
于 2013-10-26T11:26:33.203 回答
0

只是另一个应该满足您的要求的正则表达式:

<([^>]*)>
于 2013-10-26T12:46:37.263 回答
0

尝试这个:-

NSString *str =  @"<0x112233><0x112233><0x112233>0a";
NSArray *arr = [str componentsSeparatedByString:@"<"];

    NSString *str1 = [arr lastObject];

    NSArray *arr1 = [str1 componentsSeparatedByString:@">"];

    NSLog(@"array is %@",arr1);

    NSString *str2 = [[arr1 objectAtIndex:0] substringFromIndex:1];

NSString *str3=[str2 stringByReplacingOccurrencesOfString:@"0a" withString:@""];
NSLog(@"str3 is %@",str3);
[yourArray addObject:str3];
于 2013-10-26T11:21:08.977 回答