0

I would like to strip part of an NSString.

in the following string I would like to just grab the digits before the "/sampletext1/sampletext2/sampletext3"

1464/sampletext1/sampletext2/sampletext3

I have already stripped out the web address before the digits, but can't figure out the rest. Sometimes the digits could be 3 or 4 or 5 digits long.

thanks

user2588945
  • 1,681
  • 6
  • 25
  • 38

3 Answers3

6

Get the index of the first / character then get the substring up to that location.

NSString *stuff = @"1464/sampletext1/sampletext2/sampletext3";
NSString *digits;
NSRange slashRange = [stuff rangeOfString:@"/"];
if (slashRange.location != NSNotFound) {
    digits = [stuff substringToIndex:slashRange.location];
} else {
    digits = stuff;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
3

You mentioned that you extracted a web address from the front, so I'm guessing you're dealing with either something like http://localhost:12345/a/b/c or http://localhost/12345/a/b/c.

In either case, you can convert your string to an NSURL and take advantage of its built-in features:

// 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];
Brian Nickel
  • 26,890
  • 5
  • 80
  • 110
0

Use regular expressions:

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);
}
Abhinav
  • 37,684
  • 43
  • 191
  • 309