objectiveccoder001
objectiveccoder001

Reputation: 3031

Separate string into NSArray from end line

My string looks something like this:

R392P328N87R3928N32P328N123

Line end is defined by that N followed by a number.

I need to split each line into an array object. I was thinking about using simply componentsSeparatedByString: but there's a number following N and I want it to include N in the created objects.

Also notice that what comes before N is not a constant.

In other words, from that line above, I need it to create 3 array objects:

R392P328N87
R3928N32
P328N123

What's the best way to go about doing this? Should I try something that looks for 'N' and stop when it reaches another non-hex letter(I might have hexadecimal after N)?

Thanks!

Elijah

Upvotes: 0

Views: 73

Answers (1)

omz
omz

Reputation: 53551

Sounds like a job for regular expressions.

NSString *string = @"R392P328N87R3928N32P328N123";
NSString *pattern = @".*?N\\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL];
NSMutableArray *lines = [NSMutableArray array];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    [lines addObject:[string substringWithRange:result.range]];
}];
NSLog(@"%@", lines);

// => ["R392P328N87", "R3928N32", "P328N123"]

Upvotes: 1

Related Questions