Reputation: 1376
i have
NSString *str = @"<0x112233><0x112233><0x112233>0a";
i want this data to be saved in nsarray
nsarray : { 0x112233 0x112233 0x112233 }
only save data which is enclosed in "<>" and ignore all other.
i tried regex like this
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);
but i gives me this output:
data (
"<NSSimpleRegularExpressionCheckingResult: 0x1ddc5e30>{0, 30}{<NSRegularExpression: 0x1f078710> <(.*)> 0x1}"
)
Upvotes: 0
Views: 899
Reputation: 60414
Just another regex that should work with your requirements:
<([^>]*)>
Upvotes: 0
Reputation: 15335
Cool , Try this simple line of manually hardcoded without using of any reg exper.:
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);
Upvotes: 1
Reputation: 540055
(As Pat Teen said in a comment), your pattern is greedy, which means that the first match gets as much as possible, which is the entire string.
You can fix that by changing the pattern @"<(.*)>"
to @"<(.*?)>"
.
Then payloadRanges
is an array of three NSTextCheckingResult
objects:
(
"<NSSimpleRegularExpressionCheckingResult: 0x10010af40>{0, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}",
"<NSSimpleRegularExpressionCheckingResult: 0x10010c210>{10, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}",
"<NSSimpleRegularExpressionCheckingResult: 0x10010c250>{20, 10}{<NSRegularExpression: 0x100108960> <(.*?)> 0x1}"
)
Now you have to extract the substring matching the (...)
group from each result:
NSMutableArray *data = [NSMutableArray array];
for (NSTextCheckingResult *result in payloadRanges) {
[data addObject:[str substringWithRange:[result rangeAtIndex:1]]];
}
NSLog(@"data %@",data);
Output:
data (
0x112233,
0x112233,
0x112233
)
Upvotes: 5
Reputation: 15035
Try this:-
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];
Upvotes: 0