0

我想剥离一部分NSString

在以下字符串中,我只想抓取“/sampletext1/sampletext2/sampletext3”之前的数字

1464/sampletext1/sampletext2/sampletext3

我已经去掉了数字之前的网址,但无法弄清楚其余的。有时数字可能是 3 或 4 或 5 位数字。

谢谢

4

3 回答 3

6

获取第一个/字符的索引,然后将子字符串获取到该位置。

NSString *stuff = @"1464/sampletext1/sampletext2/sampletext3";
NSString *digits;
NSRange slashRange = [stuff rangeOfString:@"/"];
if (slashRange.location != NSNotFound) {
    digits = [stuff substringToIndex:slashRange.location];
} else {
    digits = stuff;
}
于 2013-09-17T21:18:30.300 回答
3

您提到您从前面提取了一个网址,所以我猜您正在处理类似http://localhost:12345/a/b/chttp://localhost/12345/a/b/c.

无论哪种情况,您都可以将字符串转换为 NSURL 并利用其内置功能:

// Port
NSURL *URL = [NSURL URLWithString:@"http://localhost:12345/a/b/c"];
NSUInteger port = URL.port.integerValue;

// Path component
NSURL *URL = [NSURL URLWithString:@"http://localhost/12345/a/b/c"];
NSString *number = URL.pathComponents[1];
于 2013-09-17T21:34:39.540 回答
0

使用正则表达式:

NSError *error;
NSString *test = @"1464/sampletext1/sampletext2/sampletext3";
NSRegularExpression *aRegex = [NSRegularExpression regularExpressionWithPattern:@"^\\d+"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:&error];

NSRange aRangeOfFirstMatch = [aRegex rangeOfFirstMatchInString:test options:0 range:NSMakeRange(0, [test length])];

if (aRangeOfFirstMatch.location != NSNotFound) {
    NSString *matchedString = [test substringWithRange:aRangeOfFirstMatch];
    NSLog(@"matchedString = %@", matchedString);
}
于 2013-09-17T21:58:34.250 回答