2013-07-20 46 views
1

我试图找到如何从“/games/usa/2013-05-01/game1.html”中提取“2013-05-01/game1”,但我不怎么做那。我已经尝试了一些正则表达式,但它没有工作。而且我也不知道这是否是最好的方法。这是我到目前为止所尝试的。如何从字符串中提取字符串?

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); 

任何帮助,将不胜感激。

+1

你能依赖围绕字符串的格式吗?它会永远像你的榜样吗? –

+0

是的,总是那样的! –

回答

4

一种方法是使用NSStringcomponentsSeparatedByString:方法。这里有一个例子

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); 

当然,这要依赖于一个事实,即格式永远不会改变,这如果是这样的变化最有可能将无法正常工作。

+1

当使用正则表达式时,90%的案例经常会过度使用。善于指出一个简单的解决方案。 – hd1

+0

@ hd1感谢您指出这一点! –

2

试试这个:

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

或本:

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

这也行得通,但我会根据@ hd1所说的答案保留另一个作为答案!但是,谢谢! –