Doug Smith
Doug Smith

Reputation: 29316

How do I extract a specific part of a string with NSRegularExpression?

Say I have a bunch of different strings:

"http://website.com/283/comments/einp43/2398/32/34/23/4/4"
"http://website.com/23283/l34/comments/inhd3/3928/3/2/3"
"http://website.com/pics/283/comments/en43/a89st/389238/a823/"
"http://website.com/pics/hd/283/comments/as87/asd7j/3"

And I always want the portion that follows comments/ which is a valuable ID. But I don't want the comments part, I just want the ID.

How do I isolate/extract that?

Upvotes: 0

Views: 118

Answers (2)

larva
larva

Reputation: 5148

You can do it with regex, try this code

NSString *string = @"http://website.com/23283/l34/comments/inhd3/3928/3/2/3";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/comments/([^/]*)" options:NSRegularExpressionCaseInsensitive error:nil];
[regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, string.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
    NSString *subStr = [string substringWithRange:[result rangeAtIndex:1]];
    NSLog(@"commentId = %@", subStr);
}];

output:

commentId = inhd3

Upvotes: 2

Lyndsey Scott
Lyndsey Scott

Reputation: 37290

Assuming the website name is stored as an NSString called websiteName:

NSArray *components = [websiteName componentsSeparatedByString:@"comments/"];  
NSString *valuableID = [components lastObject];

(Edit: I didn't notice the mention of NSRegularExpression in the title until after posting this answer, but I don't think regex is necessary in this case since you're looking for a single constant string and have no need for complex pattern recognition.)

Upvotes: 4

Related Questions