【发布时间】:2014-07-06 06:51:05
【问题描述】:
我有一个NSString,我想从这个字符串中提取两个子字符串之间的一部分。
示例字符串:https://itunes.apple.com/de/app/limbo/id656951157?l=en&mt=8
如何获取app id 656951157,在id和?之间?
【问题讨论】:
标签: ios objective-c nsstring
我有一个NSString,我想从这个字符串中提取两个子字符串之间的一部分。
示例字符串:https://itunes.apple.com/de/app/limbo/id656951157?l=en&mt=8
如何获取app id 656951157,在id和?之间?
【问题讨论】:
标签: ios objective-c nsstring
您可以将字符串转换为 URL 并获取其最后一个路径组件,而不是搜索子字符串(“id”、“?”):
NSString *urlString = @"https://itunes.apple.com/de/app/limbo/id656951157?l=en&mt=8";
NSURL *url = [NSURL URLWithString:urlString];
NSString *lastComp = [url lastPathComponent]; // id656951157
if ([lastComp length] >= 3) {
// Strip initial "id":
NSString *appId = [lastComp substringFromIndex:2];
NSLog(@"%@", appId);
// 656951157
}
【讨论】:
使用组件分隔符[yourString componentsSeparatedByString:@"id"];,它将为您提供一个包含 2 个值的数组。第二个值将是656951157?l=en&mt=8。再次使用 componentsSeparatedByString 和 ?拆分这个字符串然后你可以得到656951157。
【讨论】:
https://itunes.apple.com/de/app/xyzid/id656951157?l=en&mt=8。
使用正则表达式尝试以下操作:-
NSString *urlString = @"https://itunes.apple.com/de/app/limbo/id656951157?l=en&mt=8";
NSString *URLRegExPattern = @"(?=id).*(?=//?l=en&mt=8 )";
NSError *regExErr;
NSRegularExpression *URLRegEx =
[NSRegularExpression
regularExpressionWithPattern:URLRegExPattern
options:0
error:®ExErr];
NSRange range = [URLRegEx
rangeOfFirstMatchInString:urlString
options:0
range:NSMakeRange(0, urlString.length)];
if (!NSEqualRanges(range,
NSMakeRange(NSNotFound, 0))) {
NSString *appId = [urlString substringWithRange:range];
}
NSLog(@"appId: %@", appId);:-
【讨论】: