Guilherme Miranda
Guilherme Miranda

Reputation: 1082

How to extract a string from a string?

I'm trying to find how to extract "2013-05-01/game1" from "/games/usa/2013-05-01/game1.html", but I don't how to do that. I already tried some Regex on it but it didn't work. And I also don't know if this would be the best way. This is what I have tried so far.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/[0-9]{4}-[0-9]{2}-[0-9]-{2}\//\.*$)" options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult *newSearchString = [regex firstMatchInString:opening_time options:0 range:NSMakeRange(0, [opening_time length])];
NSString *substr = [opening_time substringWithRange:newSearchString.range];
NSLog(@"%@", substr);

Any help would be appreciated.

Upvotes: 1

Views: 81

Answers (2)

Chris Loonam
Chris Loonam

Reputation: 5745

One way would be to use NSString's componentsSeparatedByString: method. Here's an example

NSString *str = [@"/games/usa/2013-05-01/game1.html" stringByDeletingPathExtension];
NSArray *components = [str componentsSeparatedByString:@"/"];
NSString *result = [NSString stringWithFormat:@"%@/%@", [components objectAtIndex:3], [components objectAtIndex:4]];
NSLog(@"%@", result);

Of course, this would rely on the fact that the format never changes, and this most likely won't work if it does change.

Upvotes: 4

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

try this:

@"[0-9]{4}-[0-9]{2}-[0-9]{2}/[^.]+"

or this:

@"[0-9]{4}-[0-9]{2}-[0-9]{2}/.+?(?=\\.html)"

Upvotes: 2

Related Questions